Tuesday, May 08, 2018

Sed Command in Linux/Unix with examples


SED command in UNIX is stands for stream editor and it can perform lot’s of function on file like, searching, find and replace, insertion or deletion.
Though most common use of SED command in UNIX is for substitution or for find and replace.

1.Replacing or substituting string : Sed command is mostly used to replace the text in a file. The below simple sed command replaces the word "shobhit" with “sharma” in the file.

$sed 's/shobhit/sharma/' Demofile.txt

Here the “s” specifies the substitution operation. The “/” are delimiters.

By default, the sed command replaces the first occurrence of the pattern in each line and it won’t replace the second, third…occurrence in the line by this command.


2.Replacing the nth occurrence of a pattern in a line : Use the /1, /2 etc flags to replace the first, second occurrence of a pattern in a line. The below command replaces the second occurrence of the word "shobhit" with "sharma” in each line of the file.

$sed 's/shobhit/sharma/2' Demofile.txt

3.Replacing all the occurrence of the pattern in a line : The substitute flag /g (global replacement) specifies the sed command to replace all the occurrences of the string in the line.

$sed 's/shobhit/sharma/g' Demofile.txt


4.Replacing string on a range of lines : You can specify a range of line numbers to the sed command for replacing a string.

$sed '1,3 s/shobhit/sharma/' Demofile.txt

Here the sed command replaces the lines with range from 1 to 3. Another example is

       $sed '2,$ s/shobhit/sharma/' Demofile.txt

Here $ indicates the last line in the file. So the sed command replaces the text from second line to last line in the file.


5.Deleting lines from a particular file : SED command can also be used for deleting lines from a particular file. SED command is used for performing deletion operation without even opening the file


 Examples:

1. To Delete a particular line say n in this example

$ sed 'nd' Demofile.txt
Example:
$ sed '5d' Demofile.txt


2. To Delete a last line
$ sed '$d' Demofile.txt


3. To Delete line from range x to y

$ sed 'x,yd' Demofile.txt
Example:
$ sed '3,6d' Demofile.txt

5. To Delete from nth to last line

$ sed 'nth,$d' Demofile.txt
Example:
$ sed '12,$d' Demofile.txt


6. To Delete pattern matching line

$ sed '/pattern/d' Demofile.txt
Example:
$ sed '/abc/d' Demofile.txt

No comments:

Post a Comment

Clear BNE Cache for WebADI Changes

It Sometime happens that WebAdi Changes doesn't reflect once migrated in controlled instances. Here are the quick steps(Generally perfor...