Sed Examples
Sed Examples
sed Examples:
All of these examples will operate on a file named test.dat that contains the following lines of
text:
Output:
The Birthday Song
Explanation:
sed '/Happy/p' test.dat
The string to search for is delimited by / /, in this case Happy: /Happy/
The p following /Happy/p says to print out all of the lines that match the search string.
By default, sed will also print all of the lines of input, so in this example any line that
contains the string /Happy/ will be printed twice.
To print only the lines in the file that contain Happy, use the –n option:
Output:
The Birthday Song
Explanation:
sed 's/(name)/Samantha/' test.dat
The output of this sed command is a copy of every input line with the substitution edits
applied. If an input line does not match the string being replaced it will be printed
exactly as it is was read in. If the input line does have a match for the search string the
line will be printed after the edit (substitution) has been made.
To print only the lines where a substitution was applied use the p command following
the substitution: sed -n 's/(name)/Samantha/p' test.dat
Example 3: Change the string (name) with the name Samantha, and change the
order of the words so it read: Dear Samantha, Happy Birthday
Output:
The Birthday Song
The sed command is using the substitute command, the string that is being matched is
/\(.*\)Dear (name)/ which is some characters before Dear (Name)
There other ways to do this – but this example shows how to capture parts of a string.