Search This Blog

Thursday, January 22, 2009

sed examples Text manupulation using the sed

SED is very powerful command in context of text manupulation

sed 's/string1/string2/g' ------ Replace string1 with string2

sed 's/\(.*\)1/\12/g' ---------------Modify anystring1 to anystring2

sed '/ *#/d; /^ *$/d' ---------Remove comments and blank lines

sed ':a; /\\$/N; s/\\\n//; ta' ----------- Concatenate lines with trailing \

sed 's/[ \t]*$//' ----------Remove trailing spaces from lines

sed 's/\([\\`\\"$\\\\]\)/\\\1/g' --Escape shell meta characters active within double quotes

seq 10 | sed "s/^/ /; s/ *\(.\{7,\}\)/\1/" ---------Right align numbers

sed -n '1000p;1000q' ----------Print 1000th line

sed -n '10,20p;20q' -----------Print lines 10 to 20

\(.*\)sed -n 's/.*<\/title>.*/\1/ip;T;q' ------------Extract title from HTML web page

sed -i 42d ~/.ssh/known_hosts ---------------Delete a particular line

2 comments:

  1. To write a text at a particular line

    sed -i '15ivikas' file

    this will write vikas at 15th line of file

    ReplyDelete
  2. IP extracting using the sed
    If who has some ip

    who | sed 's/[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}//'

    who | sed 's/^.*[^0-9]\([0-9]*\.[0-9]*\.[0-9]*\.[0-9]*\).*$/\1/'

    who | sed -n 's/^.*[^0-9]\([0-9]*\.[0-9]*\.[0-9]*\.[0-9]*\).*$/\1/p'

    ReplyDelete