Bash Sed Scripts
A sed script is a list of sed commands saved in a file or chained on one command line. It lets one run apply many edits to a file at once.
Two edits with two -e options
Two -e options add two substitutions to one run. Each line changes only where its own pattern matches.
printf 'cat sleeps\ndog runs\n' > pets.txt
sed -e 's/cat/CAT/' -e 's/dog/DOG/' pets.txtOne script file, reused in one run
The -f option reads commands from a file. Both substitutions run on every line of the input file.
printf 's/tea/coffee/\ns/milk/cream/\n' > fix.sed
printf 'tea and milk\ntea only\n' > drinks.txt
sed -f fix.sed drinks.txtHold space swaps two lines
The first line goes into hold space with h. The second line joins it, x swaps the two lines, and the pattern swaps them back in reverse order before printing.
printf 'first line\nsecond line\n' > pair.txt
sed -n '1h;2{H;x;s/\(.*\)\n\(.*\)/\2\n\1/p}' pair.txtExample
printf '1!G\nh\n$p\n' > reverse.sed
printf 'wash dishes\ncall ana\nread book\n' > notes.txt
sed -n -f reverse.sed notes.txtKey points
- -e: an option that adds one sed command to a run.
- -f: an option that reads sed commands from a script file.
- Script file: a plain text file that holds sed commands, one per line.
- h: a command that copies the current line into hold space.
- H: a command that appends the current line to hold space.
- g: a command that copies hold space back over the current line.
- G: a command that appends hold space after the current line.
- x: a command that swaps the current line with hold space.
In this example, a script file holds three hold-space commands. The first command appends hold space to every line after the first. The second command saves the growing list back into hold space. The last command prints the whole list only on the last line, so the notes come out in reverse order.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A sed script file holds two substitutions. Which option runs it?