cool sed tricks

Remove Blank Lines from file

cat file-blanklines-2-be-deleted | sed -e '/^$/d' | tee newfile-no-blanklines

some "sed-like" tricks from within vi:


insert # at beginning of lines


:%s/.*/# &/g - inserts a # at the beginning of every line
:15,$s/.*/# &/g - inserts a # at the beginning of line 15, until the end of the file
:15,250s/.*/# &/g - inserts a # from line 15 through 250.

turn one or more blank spaces into one space

:%s/ */ /g

remove blank lines, or lines with only spaces or tabs

:g/^[ t]*$/d --> WHERE t=tab

redo entire line adding parentheses:

at command line: sed s/.*/( & )/ file > new.file or from within vi: :%s/.*/( & )/g

create a list of commands from a directory listing:

  1. ls > list cat list: list sed.html file.txt
  2. sed 's/.*/mv & &.save/' list > list2mv cat list2mv: mv list list.save mv sed.html sed.html.save mv file.txt file.txt.save
  3. rm list
  4. chmod 750 list2mv
  5. ./list2mv (to move files to *.save version, could use cp to make backup copies)

delete blank spaces:

FROM within vi: :%s/^ *\(.*\)/\1/g OR :%s$^ *\(.*\)$\1$g

delete blank lines:

sed /^$/d file > newfile FROM within vi: :g/^$/d or :%s/^$/d

some "sed-like" tricks using perl at the command line:

perl -pi -e 's/.*/# &/g' filename - inserts a # at the beginning of every line (FOR SOME REASON THE ABOVE COMMAND worked yesterday, but not today... but the command does work in vi, so I must have goofed... I remember having some notes on why it doesn't work... I'll fix this later... john. :) note: to do specific lines in perl gets a bit ugly... (as far as I know at this point) perl -pi'*.bak' -e 'if ($.==3){s/$_/Replacement text/;}' file.txt 3 is the line affected (this might work at the command line, ymmv - tested on HP) perl -pi'*.bak' -e 'if ($.==3..20){s/$_/Replacement text/;}' file.txt 3 through 20 would be affected