使用sed在行范围内查找和替换文件中的文本

时间:2021-01-07 19:32:10

I have a big text file (URL.txt) and I wish to perform the following using a single sed command:

我有一个大文本文件(URL.txt),我希望使用单个sed命令执行以下操作:

  1. Find and replace text 'google' with 'facebook' between line numbers 19 and 33.

    在第19行和第33行之间找到并将'google'替换为'facebook'。

  2. Display the output on the terminal without altering the original file.

    在不更改原始文件的情况下显示终端上的输出。

1 个解决方案

#1


7  

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 

#1


7  

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