Create a new file with
for i in {1..15}-{a..c} ; do echo this is line $i >> test-file.txt ; done
Add a newline to the beginning and end of the file
sed -e '1i\ ' -e '$a\ ' test-file.txt
Add a newline from the 3rd through to the 10th line
sed -e '3,10i\ ' -e '$a\ ' test-file.txt
Add a newline at the 3rd and 10th line
sed -e '3~10i\ ' -e '$a\ ' test-file.txt
Add to the beginning of lines 1 through 5 with
sed '1,5 s/^/Alice the Goon say'"'"'s\t/' test-file.txt <<-- Note the quotes for escaping the apostrophe.
Add to the end of lines 6 through 12 with
sed '6,12 s/$/\t I Love Popeye/' test-file.txt
Select individual lines
sed -e '13 s/^/Lucky\t /' test-file.txt -e '14 s/$/\t\tPopeye/'
Add to the beginning of every third line
sed '0~3 s/^/hello\t/g' < test-file.txt
Add to the end of every third line
sed '0~3 s/$/\tdolly/g' < test-file.txt
change the file’s line numbering now with
sed -i '=' test-file.txt "=" is a command in sed to print the current line number to the standard output.
append to the lines matching (PATTERN) “10” with
sed '/10/ a\ hello' test-file.txt
append after the line number (ADDRESS) “10” with
sed '10 a\ hello' test-file.txt
in each case
\a for append (add after match) can be changed for
\i for insert (add before match)
or \c to change the whole matching line.
example: sed '/10/ c\ hello dolly' test-file.txt
Unlike using
sed 's/is/hello dolly/g' test-file.txt OR sed 's/10/hello dolly/' test-file.txt
Finally you can re-number your file with
sed = test-file.txt | sed 'N;s/\n/\t/' OR nl testfile.txt OR cat -n testfile.txt
as always write it to a new file with > newfile-name
or use -i to edit it inline
To delete trailing whitespace from end of each line
cat input.txt | sed 's/[ \t]*$//' > output.txt
Remove all leading and trailing whitespace from each line
cat input.txt | sed 's/^[ \t]*//;s/[ \t]*$//' > output.txt
To change the nth occurrence on each line add a number at the end of the substitute command
sed 's/old/new/2' file