This page demistrates the sed Command and the syntax for the command.
Code |
Output |
sed 's/
The s stands for substitute. This tells sed to replace certain instances (that are specified by the user) with a letter, number, space, or a combination of the three.
|
No Example |
sed 's/yourword/
"Yourword" is the word that sed is looking for in the file to replace.
|
No Example |
sed 's/yourword/hi/
Once "yourword" is found, sed uses the the word, numbers, spaces or the combination of the three, that lies past the second "/" to replace the first word with the the replacement word. In other words, the instance of "yourword" will be
replaced by "hi" anywhere it is found in the file.
|
No Example |
sed 's/yourword/hi/g' filename
"g" at the end of the sed command means that it will "gloably", all instances of, and replace them with "hi". And finally, the file name is placed at the end of the sed command so that it knows what file to look in.
|
 |
sed '/yourword/d' yourFile
Any line containing "yourword" will be deleted.
|
 |
sed 's/yourword/hi/g;s/yourword2/no/g'
Writing the sed command in this format allows the user to make multiple substitutions to the stream (output) at once. Even though the command looks a bit different in this format, all the rules above apply. The user is able to
string many sed commands together by using the above format. *NOTE: Notice that the two parts of the sed command are separated by a ; (semicolon).
|
 |
sed 's/yourword/hi/' yourfile
Substitutes the first instance ONLY of yourword for each line.
|
 |
sed 'N;s/\n/ /;P;D;' yourfile
In this example N adds the next line of text to the buffer, then it substitutes (s) a space (/ /) for a new line (\n), prints the top line of the buffer (P), and finally
it deletes the top line from the work buffer and runs the script again (D).
|
 |
sed (number of user choice)d yourfile
This allows the user to delete a specific line of text from the output stream.
|
 |
sed '/^$/d' yourfile
This deletes all blank lines from a file.
|
 |
sed '2,/^$/d' yourfile
This deletes from the first line up to and including the second line.
|
 |
sed '/yourword/p' yourfile
Prints only the lines of text that contain "yourword" in them. Notice how the extra new lines interfere with the command.
|
 |
sed 's/ *$//' yourfile
Deletes all blank spaces at the end of each line of text.
|
 |
sed 's/00*/0/g' yourfile
This removes a large string of zeros and replaces them with a single zero.
|
 |
sed '/yourword/d'
Deletes all lines that contain "yourword"
|
 |