在bash中使用sed replace' oldstring'使用' newstring'

时间:2016-06-04 03:06:53

标签: string bash replace sed substitution

我有一个额外的信用卡分配,要求我用3个参数来消除他们的任务中的某个人的名字并用我的名字替换它。 第一个参数是文件名 第二个参数是" oldstring" 第三个参数是"新闻字符串"

这是我的剧本:

#!/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"用"我的名字"哪个工作得很好但是当我再次运行它以试图替换" smarty@mcsmartypants.smart \ n"用"我的@ email"没有变化。有人可以解释这种现象吗?

1 个答案:

答案 0 :(得分:0)

sed逐行匹配,因此您无法使用它来替换换行符。您似乎正在尝试替换文字\后跟n,但是,在这种情况下,您需要转义\,以便sed不会#39; t将\n视为转义序列。

比较

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

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