将一个子字符串替换为 shell 脚本中的另一个字符串 [英] Replace one substring for another string in shell script

查看:25
本文介绍了将一个子字符串替换为 shell 脚本中的另一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有I love Suzi and Marry",我想把Suzi"改成Sara".

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

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

结果一定是这样的:

firstString="I love Sara and Marry"

推荐答案

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

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

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

要替换所有,使用${parameter//pattern/string}:

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

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

(这记录在 Bash参考手册,第 3.5.3 节外壳参数扩展".)

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

注意这个特性不是由 POSIX 指定的——它是一个 Bash 扩展——所以不是所有的 Unix shell 都实现它.有关相关 POSIX 文档,请参阅 The Open Group Technical Standard Base Specifications,第 7 期Shell &实用程序卷,第 2.6.2 节参数扩展".

Note that this feature is not specified by POSIX — it's a Bash extension — so not all Unix shells implement it. For the relevant POSIX documentation, see The Open Group Technical Standard Base Specifications, Issue 7, the Shell & Utilities volume, §2.6.2 "Parameter Expansion".

这篇关于将一个子字符串替换为 shell 脚本中的另一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆