Using sed in Linux
Updated August 15, 2003
Created March 21, 2002


Autogenerated Site Map
Search this Site!:
Search this site powered by FreeFind

prev next index
^ - Beginning of Line
$ - End of Line
. - Match any character including newline
* - Multiple

The quotes used for sed is a single quote, which is right next to the double quote.

Removing trailing content from a line.  In this case, we are removing from a colon ":" to the end of the line:
sed -e 's/:.*$//'


Removing spaces from the beginning of each line:

sed -e 's/^ *//'


Making an addition to a match:
sed -e 's/match this/& add this to that/'
The ampersand (&) will repeat the matched portion

Groups in sed:
s/^.*=m/# &/
Here we will use a group using parenthesis, and will leave out the ampersand (&)
s/^\(.*\)=m/# \1 is not set/
The parenthesis around the .* makes it group 1. Then I call
group \1 in the replace portion and I can leave back the other items
in the match portion, such as the =m that I don't want.
Here's the before and after lines:
CONFIG_PARAPORT=m
# CONFIG_PARAPORT is not set

Matching possible spaces
s/^.*description *= *"//
Read the awk man page under the section "Regular Expressions" for more information.


Here's a cool one that involves swapping. This will cause the stream to become uppercase, or lowercase, depending on which direction you do the y command.
sed --silent -e "h; y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/; /${SEARCHSTRIGVARIABLE}/ { x; p; };"

The above "${SEARCHSTRINGVARIABLE} is a variable that holds the search string I am looking for. I am demonstrating here also how to use a variable in a sed operation. The specific reason I made the above sed string using the searchstring variable is because this script was re-usable, then depending on how SEARCHSTRING was set I was able to get the results I needed. In this case SEARCHSTRING has it's value in all caps. If I converted everything to lowercase then SEARCHSTRING would have whatever I'm looking for as lowercase.

The purpose of the above (h - hold, x - exchange) is to do the search based on all caps, then print out the original entry unchanged. We don't want to change the entry to be all caps, we just want to search it and print if it matches.
prev next index
Search this Site!:
Search this site powered by FreeFind

Homepage: http://www.cpqlinux.com
Site Map: http://www.cpqlinux.com/sitemap.html