Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 views
in Technique[技术] by (71.8m points)

bash - 将一个子字符串替换为Shell脚本中的另一个字符串(Replace one substring for another string in shell script)

I have "I love Suzi and Marry" and I want to change "Suzi" to "Sara".

(我有“我爱Suzi和结婚”,我想将“ Suzi”更改为“ Sara”。)

#!/bin/bash
firstString="I love Suzi and Marry"
secondString="Sara"
# do something...

The result must be like this:

(结果必须是这样的:)

firstString="I love Sara and Marry"
  ask by Zincode translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To replace the first occurrence of a pattern with a given string, use ${ parameter / pattern / string } :

(要用给定的字符串替换第一次出现的模式,请使用${ parameter / pattern / string } :)

#!/bin/bash
firstString="I love Suzi and Marry"
secondString="Sara"
echo "${firstString/Suzi/$secondString}"    
# prints 'I love Sara and Marry'

To replace all occurrences, use ${ parameter // pattern / string } :

(要替换所有出现的内容,请使用${ parameter // pattern / string } :)

message='The secret code is 12345'
echo "${message//[0-9]/X}"           
# prints 'The secret code is XXXXX'

(This is documented in the Bash Reference Manual , §3.5.3 "Shell Parameter Expansion" .)

((这在Bash参考手册的第 3.5.3节“ Shell参数扩展”中进行了介绍 。))

Note that this feature is not specified by POSIX — it's a Bash extension — so not all Unix shells implement it.

(请注意,POSIX未指定此功能-它是Bash扩展-因此并非所有Unix Shell都实现此功能。)

For the relevant POSIX documentation, see The Open Group Technical Standard Base Specifications, Issue 7 , the Shell & Utilities volume, §2.6.2 "Parameter Expansion" .

(有关相关的POSIX文档,请参见《 Open Group技术标准基本规范》第7期Shell&Utilities卷,第2.6.2节“参数扩展” 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...