SED Command
SED ( Stream editor) : A special editor for modifying files automatically. It has similarity with the “Find” and “Replace” command available in windows notepad/wordpad.
sed command can be used to search and manipulate input text in many ways. Though mainly used for substitution, it can also do numerous other pattern matching tasks like searching and printing lines which matches a pattern, removing lines which matches a pattern, deleting specific lines in the input file etc.
Sed has several command options . Some of the command options are below as examples.
Consider the file test.log
server501:[DATA001] /home/oracle -> cat test.log
ANJELINA IS A GOOD GIRL
RAMU IS A GOOD BOY
DIYA IS A GOOD GIRL
s for substitution
1. Replace GOOD with BAD and save it to a new file.
server501:[DATA001] /home/oracle -> sed s/GOOD/BAD/ test.log > test1.log
server501:[DATA001] /home/oracle -> cat test1.log
ANJELINA IS A BAD GIRL
RAMU IS A BAD BOY
DIYAIS A BAD GIRL
>>> Here GOOD is replaced with BAD and saved to an new file test1.log. Sed command has taken test.log as the input and test1.log as output
server501:[DATA001] /home/oracle -> sed s/GOOD/BAD/ test.log > test1.log
server501:[DATA001] /home/oracle -> cat test1.log
ANJELINA IS A BAD GIRL
RAMU IS A BAD BOY
DIYAIS A BAD GIRL
>>> Here GOOD is replaced with BAD and saved to an new file test1.log. Sed command has taken test.log as the input and test1.log as output
2. Print the same output as below in the screen without saving into a new file
server501:[DATA001] /home/oracle -> sed s/GOOD/BAD/ test.log
ANJELINA IS A BAD GIRL
RAMU IS A BAD BOY
DIYA IS A BAD GIRL
d to delete lines from a file
Consider new file file1.log with the below data
server501:[DATA001] /home/oracle -> cat file1.log
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
1. Print the output after deleting the 1st line from the file
server501:[DATA001] /home/oracle -> sed ‘1d’ file1.log
This is line 2
This is line 3
This is line 4
This is line 5
2. Print the output after deleting the last line from the file
server501:[DATA001] /home/oracle -> sed ‘$d’ file1.log
This is line 1
This is line 2
This is line 3
This is line 4
3. Print the output after deleting the lines from 2 to 4 from the file
server501:[DATA001] /home/oracle -> sed ‘2,4d’ file1.log
This is line 1
This is line 5
AWK command has more usages compared to sed. SED is mainly for editing and pattern matching, where as in AWK, we can incorporate functions, arrays etc.