Monday, August 24, 2009

Simple useful sed commands

Here is the Ultimate sed command list ;)

- Replace all A's by B's and write file

sed -i 's/A/B/g' file
sed -i 's|A|B|g' file

- Insert a # at the first of the line with the pattern
sed -o 's/.*A.*/#&/g'

- Delete all lines containing ABC

sed -i '/ABC/d' file

- Show only lines containing ABC (like grep) (Dangerous if you use the -i flag)

sed '/ABC/!d' file
sed -n '/ABC/p' file

- Delete all blank lines

sed -i '/^$/d'

- Delete third line

sed -i '3d' file

- Delete from second to third line

sed -i '2,3d' file

- Delete all but line 3 to line 5 (Keeping lines 1,2,5,6 ...)

sed -i '3,5!d' file

- Delete from first to first ocurrence of ^$ (Blank line)

sed -i '1,/^$/d' file

- Find all ABC and append a line with ZZZ after that

sed -i '/ABC/aZZZ' file

- Find all ABC and insert a line before ZZZ

sed -i '/ABC/iZZZ' file

- Find all ABC change ALL the line for a ZZZ (Be warned!)

sed -i '/ABC/cZZZ' file

- Print line number and line with A

sed -n '/A/{=;p}' file

- Print all line numbers before all lines

sed '=' file

- Just like head... Print the 10 first lines of a file

sed 10q file

- Group commands

sed -i 's|A|B|g;s|Z|Y|g' file
sed -i '
s|A|B|g
s|Z|Y|g' file

PD: be carefull with especial characters (*,.,;, etc), change them to \* \. \; . Always check your pattern with sed -n "/PATTERN/" file

No comments: