bash 使用sed在行范围之间查找和替换文件中的文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36149036/
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
Find and replace text in a file between range of lines using sed
提问by Suraj Bhatia
I have a big text file (URL.txt) and I wish to perform the following using a single sedcommand:
我有一个大文本文件 (URL.txt),我希望使用单个sed命令执行以下操作:
Find and replace text 'google' with 'facebook' between line numbers 19 and 33.
Display the output on the terminal without altering the original file.
在第 19 行和第 33 行之间查找文本“google”并将其替换为“facebook”。
在终端上显示输出而不改变原始文件。
回答by andlrc
You can use SED's range selector for that:
您可以使用 SED 的范围选择器:
sed '19,33{s/google/facebook/}' file
This will run the substitution on lines between 19 (exclusive) and 33 (inclusive)
这将在 19(不包括)和 33(包括)之间的行上运行替换
Note this will only replace the first occurrence of google
on each line, you can use the g
-modifier to change this behavior:
请注意,这只会替换google
每一行中第一次出现的,您可以使用g
-modifier 来更改此行为:
s/google/facebook/g
回答by CharMstr
the above answer ALMOST worked for me on Mac OSX.
上面的答案几乎在 Mac OSX 上对我有用。
sed '19,33s/google/facebook/' file
sed '19,33s/google/facebook/' 文件
worked perfectly without braces.
没有牙套也能完美工作。
sed '19,$s/google/facebook/' file
sed '19,$s/google/facebook/' 文件
works until the end of the file as well.
也可以工作到文件末尾。