Saturday, December 21, 2013

Sed Cheat Sheet

Great sed Resources (there are many other helpful sites)
http://sed.sourceforge.net/sed1line.txt
http://www.unixguide.net/unix/sedoneliner.shtml


Sed one-liner commands I use often
Create a backup file then inline edit the original file.
sed -i<append to filename> 's/text to match/replace with text/g' filename

The following example creates a file called "simpsonsfile.bak", then inline
edits the original "simpsonsfile", replacing each instance of "homer" with "marge".
Ex: sed -i.bak ‘s/homer/marge/g’ simpsonsfile

Insert at the beginning of a specific line.
sed '1 s/^/text to insert/' filename

Append to the end of a line with matching text.
sed ‘text to match/s|$|text to append|’ filename

Append to the end of a specific line.
sed 'line# s/$/text to append/' filename

Replace multiple matches with one sed call.
sed -e 's/match1/replace1/g' -e 's/match2/replace2/g' filename

Print / display a given line from a file.
sed -n '<line#>p' filename

Print / display a range of lines of a file.
sed -n '<starting line#>,<ending line#>p' filename

The following example prints lines 2 through, and including, 5 of the file.
Ex: sed -n '2,5p' simpsonsfile

Use double quotes when using variables in a sed command
sed "s/text to match/$my_variable/g" filename


Remove white space or blank spaces in text.
echo 'some text with blank spaces' | sed 's/ *//g'
returns: sometextwithblankspaces

Remove leading spaces or tabs from the beginning of a line.
sed -e 's/^[ \t]*//;s/[ \t]*$//' filename

Remove trailing spaces from the end of a line.
sed 's/[ \t]*$//' filename

Remove blank / empty lines from a file.
sed '/^$/d' filename
or
sed '/./!d' filename

Remove entire line from a file when it has text that matches.
sed '/text to match/d' filename

Edit the last line of a file.
sed '$ s/text to match/replace with text/g' filename

Print the line with matching text and all lines after to the end of the file.
sed -n -e '/text to match/,$p' filename

Print the lines AFTER the line containing the matching text till the end of the file.
sed -e '1,/text to match/d' filename

Print the lines BEFORE the line containing the matching text.
sed -e '/text to match/,$d' filename



No comments:

Post a Comment