Sed examples explaining different options.
-n Suppress automatic printing of pattern space. Explicitly use 'p' to print pattern space. -e Prints out the pattern space at the end of each cycle. -f Add the commands contained in a script file to the set of commands to be run. -i This option specifies that files are to be edited in-place.
In below two examples sed is invoked with silent option (-n).
Example 1: No output as sed is invoked with silent mode.
bash-3.2$ sed -n '' test.txt bash-3.2$
Example 2: To print all the contents of the file issue command ‘p’ with silent option (-n).
bash-3.2$ sed -n 'p' test.txt 1. leaf is green 2. sky is blue 3. snow is white 4. moon is white 5. flower is yellow bash-3.2$
In below example sed is invoked with -e (expression) option.
Example 3: This prints all the contents of the file. With -e option and with empty commands ”, sed prints out the pattern space at the end of every cycle.
bash-3.2$ sed -e '' test.txt 1. leaf is green 2. sky is blue 3. snow is white 4. moon is white 5. flower is yellow bash-3.2$
Example 4: By default sed prints the pattern space at the end of every cycle.
Note: No option has been specified.
bash-3.2$ sed '' test.txt 1. leaf is green 2. sky is blue 3. snow is white 4. moon is white 5. flower is yellow bash-3.2$
Example 5: In the below example we are invoking sed using -f (script-file) option.
For this purpose lets create a file called sed_commands with some commands. Lets add commands to delete 3rd and 5th line.
After executing the sed_commands using -f option, note the lines 3 and 5 have been deleted in the output.
This command however deletes the lines only in pattern space and the actual file test.txt remain untouched.
bash-3.2$ cat sed_commands 3d 5d bash-3.2$ sed -f sed_commands test.txt 1. leaf is green 2. sky is blue 4. moon is white
Example 6: In the below example, sed is invoked using -i option.
This command directly edits test.txt and line 3 is deleted using the command 3d.
Note the line 3 is deleted from the actual file itself.
bash-3.2$ sed -i '3d' test.txt bash-3.2$ cat test.txt 1. leaf is green 2. sky is blue 4. moon is white 5. flower is yellow bash-3.2$