Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  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.

like image 822
Suraj Bhatia Avatar asked Mar 22 '16 08:03

Suraj Bhatia


People also ask

How do I use sed to find and replace text in a file?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.

Does sed support multiline replacement?

By default, when sed reads a line in the pattern space, it discards the terminating newline (\n) character. Nevertheless, we can handle multi-line strings by doing nested reads for every newline.

How do you use multiple lines in sed?

By using N and D commands, sed can apply regular expressions on multiple lines (that is, multiple lines are stored in the pattern space, and the regular expression works on it): $ cat two-cities-dup2.


1 Answers

You can use sed addresses:

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

This will run the substitution on lines between and including 19 and 33.

The form of a sed command is as follows:

[address[,address]]function[arguments]

Where 19,33 is the addreses,
substitute is function
and global is the argument

like image 106
Andreas Louv Avatar answered Sep 19 '22 02:09

Andreas Louv