【问题标题】:Bash script replacing arbitrary input strings with arbitrary output strings containing spaces via sedBash 脚本通过 sed 将任意输入字符串替换为包含空格的任意输出字符串
【发布时间】:2017-11-24 17:35:08
【问题描述】:

我是 Bash 新手,我正在尝试创建一个 bash 函数,它可以:

1) 在我当前目录的子文件夹中递归查找与给定 ($1) 匹配的所有文件名

2) 找到与变量字符串 ($2) 中的模式匹配的整行并将其替换为第二个变量字符串 ($3)

我想我已经完成了大部分工作,但是在替换包含空格的文本字符串时遇到了麻烦。我当前的功能如下:

rplcPhrase() {
    find . -name $1 -exec sed -i "/$2/c $3" {} + 
}

rplcPhrase $1 $2 $3

命令行输入看起来像

/link/to/file.sh "filetochange.txt" "\!phrase[[:space:]]to[[:space:]]change" "replacement[[:space:]]phrase"

对类似问题的研究已经解释了需要“转义”特殊字符(例如“!”)才能在模式中使用,并且必须在搜索模式中使用 [[:space:]] 以说明空格。但是,我想返回一个包含空格的短语。上面命令行输入的结果正确找到了模式

!phrase to change

但是用

代替
replacement[[:space:]]phrase

如果我改为将replacement[[:space:]]phrase 更改为replacement phrase,它只会产生

replacement

就像我说的,我觉得我快到了,只是缺少一些简单的东西。任何帮助,将不胜感激。

我已经对此进行了搜索,但找不到完全解决我的问题的解决方案。见链接: Replace whole line containing a string using Sed

Using sed to replace text with spaces with a defined variable with slashs

【问题讨论】:

  • 引用你的变量。
  • @Barmar 我应该在哪里引用变量?在 sed 命令中 (sed -i "/"$2"/c "$3"")?

标签: string bash sed replace


【解决方案1】:

您需要引用变量以防止分词和通配符扩展。

rplcPhrase() {
    find . -name "$1" -exec sed -i "/$2/c $3" {} + 
}

rplcPhrase "$1" "$2" "$3"

【讨论】:

  • 修复了它。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-21
  • 2016-12-24
  • 2017-12-03
  • 1970-01-01
  • 2014-04-09
  • 1970-01-01
相关资源
最近更新 更多