...

Thursday, February 25, 2010

Debian 9

GREP is for filtering. AWK can do filtering and can single out columns. SED is for search and replace. SED is known as a stream editor. SED operates on data received via STDIN ("<"), Pipe or a file. SED is used for transforming text, and is primarily used in search and replace applications although it has other functionalities. Its pattern matching is similar to GREP and AWK, and it works with POSIX and EREGEXP. SED is pattern/procedure based.
The general syntax of SED is:
sed [options] 'instruction' file

When used through pipe, you don't need to specify the file. sed can be run interactively or non-interactively (scripted). Suppose we are using the same file again:
Debian
Debian Linux
Debian2010
SUSE Linux
debian
dEbIaN
DEBIAN
SUSE Linux 9999
Debian9
Debian9 Linux
Linux SUSE 10

To print the first line from a text file:
sed -n '1p' test.txt

1p is an instruction which means print the first line. To print the last line of a file, use:
sed -n '$p' test.txt

To automatically pass the most recently used parameters into a certain program, use:
!sed

This works for every program.

Use -n to suppress lines that sed has parsed, and ALWAYS use 'p' to print affected lines.

You can also use sed to print a range of lines like this:
sed -n '4,$p' test.txt

This would print from line 4 to the last line. You can also use REGEXP in sed, like this:
sed -n -e '/SUSE/p'

In REGEXP, . means 1 character. If you want to search for the last line, you can use quantifiers like:
sed -n -e '/.* SUSE [0-9]\+/p' test.txt

You can also search for multiple patterns like:
sed -n -e '^SUSE/,/^Debian/p' test.txt

Sed is able to delete lines on input stream on output. Sed does not overwrite source files unless '-i.bak' is used. sed sends all output to STDOUT unless redirection is used. To delete lines from input stream on output:
sed -e '/SUSE/Id' test.txt > test2.txt

"I" is used to specify case insensitivity, and "d" is for delete. You can also use sed to remove ranges of lines:
sed '1,3d' test.txt > test2.txt

You can also use sed to remove blank lines:
sed -e '/^$/d' test.txt > test2.txt

Sed can also be used to replace text. We will now replace blank lines with the word "Blank". The syntax is 's/find/replace/'. We can do this by:
sed -e 's/^$/Blank Line/' test.txt > test2.txt

To search for SUSE and replace it with Novell SUSE:
sed -e 's/SUSE/Novell &/I' test.txt > test2.txt

& is equal to the search term. By default, only the first match per line will be replaced. To make multiple replacements per line, we will need to use the global option:
sed -e 's/SUSE/Novell &/Ig' test.txt > test2.txt

"g" parameter will allow global line replacements.

No comments :

Post a Comment

<