Thursday, June 25, 2009

sed Samples

Quick Examples:

General Syntax:
sed -option 'general expression' [data-file]
sed -option sed-script-file [data-file]

Option can be:

OptionMeaningExample
-eRead the different sed command from command line.
$ sed -e 'sed-commands' data-file-name
$ sed -e 's/test/TEST/' File
$ sed -e

-fRead the sed command from sed script file.
$sed -f
$ sed -f chgdb.sed friends.tdb
-nSuppress the output of sed command. When -n is used you must use p command of print flag to explicitly specify what is to be printed.$ sed -n '/^\*..$/p'

Search and replace:

$ sed 's/Linux/UNIX/' TestFile > file.out

here 's' is the search command and '/' is the delimiter used to separate the text to be searched and replaced.

Deleting blank lines

Using sed you can delete all blank line from file as follow
$ sed '/^$/d' demofile1
Here the pattern /^$/, match blank line and d, command deletes the blank line.

Using Regular Expressions with sed

$ sed -n '/10\{2\}1/p' TestFile

prints 1001, search pattern \{2\}.
Syntax:
\{n,\}
At least nth occurrences will be matched. So /10\{2\} will look for 1 followed by 0 (zero) and \{2\}, tells sed look for 0 (zero) for twice.

Matching any number of occurrence

Syntax:
\{n,\m}
Matches any number of occurrence between n and m.

Example:
$ sed -n '/10\{2,4\}1/p' TestFile2
1001
10001
100001
Will match "1001", "10001", "100001" but not "101" or "10000000".

$ sed -n '/^\*..$/p' demofile2
***
***
Above command prints all lines that begins with *** (three stars or asterisks),

Explanation:
Command
Explanation
^Beginning of line
\* Find the asterisk or star (\ remove the special meaning of '*' metacharacter)
..

Followed by any two character (you can also use \*\* i.e. $ sed -n '/^\*\*\*$/p' demofile2 )

$

End of line (So that only three star or asterisk will be matched)

/pPrint the pattern.

Also the following expression can be used for the same purpose
$ sed -n '/^\*\{2,3\}$/p' TestFile2

Following command finds out lines between *** and *** and then delete all those line
$sed -e '/^\*\{2,3\}$/,/^\*\{2,3\}$/d' demofile2 > /tmp/fi.$$
$cat /tmp/fi.$$


Above expression can be explained as follows

ExpressionMeaning
^Beginning of line
\* Find the asterisk or star (\ remove the special meaning of '*' metacharacter)
\{2,3\}Find next two asterisk
$End of line
,Next range or search pattern
^\*\{2,3\}$Same as above
dNow delete all lines between *** and *** range


No comments:

Post a Comment