bash 替换文件第 n 行中的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32325121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replacing a string in nth line a file
提问by Ravichandra
Hi need to replace a string in file only in nth lineof file
嗨需要替换文件中的字符串仅在第n行的文件
file1
文件 1
hi this is line 1
hi this is line 2
hi this is line 3
hi this is line 4
I need to replace 'hi' only in line 2
我只需要在第 2 行替换 'hi'
experted as below
专家如下
hi this is line 1
Hello this is line 2
hi this is line 3
hi this is line 4
I tried by creating a temp file
我尝试通过创建一个临时文件
sed -n 2p file1 > temp1
perl -pi -e 's/hi/Hello/g' temp1 \I tried to replace temp1 with line 2 in file1
sed -i '2d' file1 \after this I failed to insert temp1 as a 2nd line in file1
Help me to replace a string in file in Nth line(without temp file is preferred.. ).
帮我替换第 N 行文件中的字符串(首选不带临时文件..)。
Thank you
谢谢
回答by potong
This might work for you:
这可能对你有用:
sed -i '2s/hi/Hello/' file
回答by rohitkulky
Above answer is correct, but I am tempted to put AWK variant just for reference.
上面的答案是正确的,但我很想把 AWK 变体仅供参考。
awk 'NR==2{gsub("hi","Hello",)}; {print ##代码##}' file > newfile