What he sed

Q I have a large file containing 800-900 lines. Now I want to write a script that can find a particular expression in the file and then change or replace the one word in that line and another word in line below that particular line. For example, if a file contains

I am in London
Family is in Canada

I want to find the expression "in London" and replace "I am" with "You are" and in the below line I want to replace the "Family is" with "girlfriend in". I took such expressions because my search may be a expression containing spaces and replacement also contain replacement of whole sentences.

A Sed (Stream Editor) is the program you need. This can replace, delete or otherwise manipulate data in a file using regular expressions. The simplest replacement is something like

sed 's/I am/You are/' myfile >newfile

This is the most common usage of Sed, to replace occurrences of a string with another, but you have asked for something far more specific, to only replace on lines containing a string and the following lines. This can be done by limiting the command used to an address range. The command used here is s, the substitution command, and in the above example is applied to every line of the file. To limit its application, you prefix is with an address range, which can be a pair of line numbers, except you don't know the line numbers in this case, so we use

sed '/in London/,+1s/I am/You are/' myfile >newfile

Here the address range consists of two components, separated by a comma. The first is a pattern match, defined by the slashes surrounding the string, so it matches any line containing "in London". The second component is +1, which extends the range to one line after the line that starts the range. You can use any number here, but each line can only be in one range. So if lines 3, 4 and 7 match, the above command would be applied twice, first to lines 3 and 4 and then to lines 7 and 8. All other lines are passed through unchanged. The address is followed by the s command. In this example, we make only one substitution, to apply multiple commands to the addresses range, enclose them in braces, separated with semicolons. This will do just what you are asking for.

sed '/in London/,+1{s/I am/You are/ ; s/Family is/Girlfriend/}' myfile >newfile

In each case, we have redirected the output to a new file. Sed has a -i option to edit the file in place, but don't use this until you are sure your syntax is correct or you have a backup of the original file, as a slight typo could destroy your data. Sed doesn't replace the file until the command is complete, so a syntax error will leave the file unchanged, but a valid command that doesn't do what you expect it to would cause a problem. Sed is very powerful but the man page is basic, so read either the info docs or http://sed.sourceforge.net.

Back to the list