Wednesday, February 16, 2011

Some commonly used SED oneliners

Commonly used SED one liners

# double space a file
sed G

# triple space a file
sed 'G;G'

# remove double-spacing
sed 'n;d'

# count lines
sed -n '$='

# convert DOS newlines (CR/LF) to Unix format
sed 's/.$//'

# delete leading whitespace (spaces, tabs) from begining of each line
sed 's/^[ \t]*//'

# delete trailing whitespace (spaces, tabs) from end of each line
sed 's/[ \t]*$//'

# delete BOTH leading and trailing whitespace from each line
sed 's/^[ \t]*//;s/[ \t]*$//'

# substitute "chit" with "chat" on each line
sed 's/chit/chat/' # replaces only 1st instance in a line
sed 's/chit/chat/2' # replaces only 2nd instance in a line
sed 's/chit/chat/g' # replaces ALL instances in a line

# substitute "chit" with "chat" ONLY for lines which contain "tea"
sed '/tea/s/chit/chat/g'

# substitute "chit" with "chat" EXCEPT for lines which contain "tea"
sed '/tea/!s/chit/chat/g'

# print first 5 lines of file
sed 5q

# print first line of file
sed q

# print last 10 lines of file
sed -e :a -e '$q;N;11,$D;ba'

# print last line of file
sed '$!d'

# print only lines which match regular expression
sed -n '/pattern/p'
or
sed '/patttern/!d'

# print only lines which do NOT match pattern
sed -n '/pattern/!p'
sed '/pattern/d'

No comments: