Next: , Up: sed addresses   [Contents][Index]


4.1 Addresses overview

Addresses determine on which line(s) the sed command will be executed. The following command replaces the word ‘hello’ with ‘world’ only on line 144:

sed '144s/hello/world/' input.txt > output.txt

If no addresses are given, the command is performed on all lines. The following command replaces the word ‘hello’ with ‘world’ on all lines in the input file:

sed 's/hello/world/' input.txt > output.txt

Addresses can contain regular expressions to match lines based on content instead of line numbers. The following command replaces the word ‘hello’ with ‘world’ only in lines containing the word ‘apple’:

sed '/apple/s/hello/world/' input.txt > output.txt

An address range is specified with two addresses separated by a comma (,). Addresses can be numeric, regular expressions, or a mix of both. The following command replaces the word ‘hello’ with ‘world’ only in lines 4 to 17 (inclusive):

sed '4,17s/hello/world/' input.txt > output.txt

Appending the ! character to the end of an address specification (before the command letter) negates the sense of the match. That is, if the ! character follows an address or an address range, then only lines which do not match the addresses will be selected. The following command replaces the word ‘hello’ with ‘world’ only in lines not containing the word ‘apple’:

sed '/apple/!s/hello/world/' input.txt > output.txt

The following command replaces the word ‘hello’ with ‘world’ only in lines 1 to 3 and 18 till the last line of the input file (i.e. excluding lines 4 to 17):

sed '4,17!s/hello/world/' input.txt > output.txt

Next: , Up: sed addresses   [Contents][Index]