Find and replace text in a file between range of lines using sed

眉间皱痕 提交于 2020-04-04 14:05:12

问题


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

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

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


回答1:


You can use SED's range selector for that:

sed '19,33{s/google/facebook/}' file

This will run the substitution on lines between 19 (exclusive) and 33 (inclusive)

Note this will only replace the first occurrence of google on each line, you can use the g-modifier to change this behavior:

s/google/facebook/g 



回答2:


the above answer ALMOST worked for me on Mac OSX.

sed '19,33s/google/facebook/' file

worked perfectly without braces.

sed '19,$s/google/facebook/' file

works until the end of the file as well.



来源:https://stackoverflow.com/questions/36149036/find-and-replace-text-in-a-file-between-range-of-lines-using-sed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!