简体   繁体   English

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

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

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.在终端上显示输出而不改变原始文件。

You can use sed addresses:您可以使用 sed 地址:

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

This will run the substitution on lines between and including 19 and 33.这将在 19 和 33 之间(包括 19 和 33)的行上运行替换。

The form of a sed command is as follows: sed命令的形式如下:

[address[,address]]function[arguments]

Where 19,33 is the addreses,其中19,33是addreses,
s ubstitute is function s ubstitute是功能
and g lobal is the argumentg叶形是参数

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.也可以工作到文件末尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM