Post Reply 
 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Some basic sed print examples
12-28-2009, 08:07 PM
Post: #1
Some basic sed print examples
First let me show you explain some special characters in sed that I will use in this example.

$ - is that special character meaning the end of a line
^ - is a special character meaning the beginning of a line
. - means any character of the character before it or nothing. Example [a-z]. means any character from a-z
? - mean any character

Since everybody has a /etc/passwd on unix systems. I will use that file for displaying data.

First lets go over the print command in sed. sed will print command prints any pattern that match. You need to use the -n parameter when printing or it will just print duplicates for lines found.

Say you only wan to print certain lines in a file. The code below will print the first 2 lines in the passwd file
Code:
sed -n 1,2p /etc/passwd

If you want to print line from 2 to 5 you would do this
Code:
sed -n 2,5p /etc/passwd

If you want to print lines 4 to the end you would do this. Notice when using special characters you need to use single quotes because bash may also use this single character. It is a good habit to just put everything in single quotes.
Code:
sed -n '4,$' /etc/passwd

Now that we got out how to printing a range of lines. Let print matching cases. say you want to see all the user using the bash you would do as follows. You would put you patter in between / / followed by a p. This code below only prints lines that has the word bash in it
Code:
sed -n '/bash/p'

If you want to print all lines that begin with a s you would do as follows. Remember that the ^ is a special character meaning beginning. If you did not put this in there it will just look through the online line and any line that had a s would be printed
Code:
sed -n '/^s/p' /etc/passwd

If you want to print a line that has any character that start with a range of characters you can do this. This command will start for any lines that begin with a or a r
Code:
sed -n '/^[ar]/p' /etc/passwd

If you wanted to print a line that has a word that had r and t in it with any 2 character in between you would do to this. Remember the ? mean any character. If you have root installed you probably will find that line Smile
Code:
sed -n '/r??t/p' /etc/passwd

my last printing example is print between b and h with any range of characters in between. This will print any lines that a r and t after the r
Code:
sed -n '/r.*t/p' /etc/passwd

There is so much more you can do with sed with printing but this is the basics
Visit this user's website Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump:


 Quick Theme: