【问题标题】:in bash using sed replace 'oldstring' with 'newstring'在 bash 中使用 sed 将 'oldstring' 替换为 'newstring'
【发布时间】:2016-10-04 04:51:11
【问题描述】:

我有一个额外的学分作业,要求我使用 3 个参数来去除作业中某人的姓名,并将其替换为我的。 第一个参数是文件名 第二个参数是“旧字符串” 第三个参数是“newstring”

这是我的脚本:

#!/bin/bash
file=$1
oldname=$2
newname=$3
changed=`grep -R "$oldname" $file | sed -i "s/$2/$3/g" $file`
done

这是我正在搜索的文件

int main(int argc, char**argv)
{
printf("Assignment #3-4, Smarty McSmartypants, smarty@mcsmartypants.smart\n");
printf("%0.4f\n",cos(sqrt(atoi(argv[1]))/10.0f));'

我将用“我的名字”替换“Smarty McSmartypants”,效果很好,但是当我再次运行它以尝试用“my@email”替换“smarty@mcsmartypants.smart\n”时,没有任何变化。有人可以解释这种现象吗?

【问题讨论】:

  • 您认为其标准输入来自grep -R "$oldname" $file 会如何改变sed -i "s/$2/$3/g" $file 的行为?
  • 至于您的直接问题,尽管 -- sed 不采用文字字符串,它采用 regexes。不是一回事。 \n 作为正则表达式与 \n 作为文字不匹配。
  • 还有吗?引用您的扩展,包括文件名。 "$file",不是$file;否则,带有空格的文件名将被分解为多个参数。
  • ...如果您想进行文字字符串替换,顺便说一句,有很好的工具可以完成这项工作,但sed 不是其中之一。请参阅mywiki.wooledge.org/BashFAQ/021 的 BashFAQ #21 进行全面讨论。

标签: string bash replace sed substitution


【解决方案1】:

sed 逐行匹配,因此您不能使用它来替换换行符。看起来您正在尝试替换文字 \ 后跟 n,但是,在这种情况下,您需要转义 \ 以便 sed 不会将 \n 视为转义顺序。

比较:

$ echo 'foo\nbar' | sed 's/foo\n/fib/g'
foo\nbar

$ echo 'foo\nbar' | sed 's/foo\\n/fib/g'
fibbar

【讨论】:

    猜你喜欢
    • 2013-08-31
    • 2019-07-20
    • 1970-01-01
    • 2020-09-22
    • 2011-12-02
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    相关资源
    最近更新 更多