bash - 将一个子字符串替换为 shell 脚本中的另一个字符串

标签 bash shell

我有“我爱苏子和结婚”,我想把“苏子”改成“萨拉”。

firstString="I love Suzi and Marry"
secondString="Sara"

期望的结果:

firstString="I love Sara and Marry"

最佳答案

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

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

要替换出现的所有,请使用${<em>parameter</em>//<em>pattern</em>/<em>string</em>} :

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

(这记录在 the Bash Reference Manual, §3.5.3 "Shell Parameter Expansion" 中。)

请注意,此功能不是由 POSIX 指定的 — 它是 Bash 的扩展 — 因此并非所有 Unix shell 都实现它。有关相关的 POSIX 文档,请参阅 The Open Group Technical Standard Base Specifications, Issue 7, the Shell & Utilities volume, §2.6.2 "Parameter Expansion" .

关于bash - 将一个子字符串替换为 shell 脚本中的另一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13210880/

相关文章:

c - 如何创建将 stdin 重定向到子进程的代理进程?

linux - 在命令行中 sftp 两个文件

linux - 如何去除文件名中的特殊字符?

windows - 如何通过 Windows 命令行 shell 脚本保持文件打开(锁定)?

haskell - 如何将 GHC 安装到 Cygwin 或将 Cygwin 指向 GHC?

python - 在终端中运行 python 会出现错误的版本

linux - 在 Linux 中以编程方式创建的文件变为 NULL

python - 如何在 google Colab 中运行脚本 shell?

linux - 如何知道要使用什么脚本头以及它为什么重要?

bash - 在 shell 程序脚本中继续之前,如何等待 “docker exec ”完成