Understanding sed Command
This post helps Understanding sed Command. sed command stands for stream editor and is used to search, find and replace, insert or delete a string. Generally, it is used to replace a particular pattern or text in a file. In short, we can edit files even without opening it using sed command.
sed 's/place/city/' newfile.txt
In the above example, sed command replaces the word “place” with “city” in the file “newfile.txt”.
Here “place” is the search pattern, “city” is the replacement string and ‘/’ is the delimiter. By default, sed command replaces only the first occurrence of the pattern in each line
Replace nth occurrence of a pattern:
If you want to replace only the second occurrence of a pattern or only the third occurrence of a pattern in a line, you can use the following command:
sed 's/place/city/2' newfile.txt
sed 's/place/city/3' newfile.txt
Replace all the occurrence of a pattern:
If you want to replace all the occurrences of a pattern in a line:
sed 's/place/city/g' newfile.txt
Replace from nth occurrence to all occurrences:
If you want to replace all the patterns from the 3rd occurrence to all the subsequent occurrences in a line:
sed 's/place/city/3g' newfile.txt
Replace the string on a specific line:
To replace the string ‘place’ only on line 3 with ‘city’:
sed '3 s/place/city/' newfile.txt
Duplicate the line which has the search pattern:
To duplicate all the lines which have the search pattern use the /p flag:
sed 's/place/city/p' newfile.txt
Print only the replaced lines:
Use -n option along with /p flag to suppress the duplicate lines and print only the replaced lines.
sed -n 's/place/city/p' newfile.txt
Replace string on a range of lines:
sed '1,3 s/place/city/' newfile.txt
Here the string will be replaced from line 1 to line 3
sed '3,$ s/place/city/' newfile.txt
‘$’ sign indicates the last line.
The string will be replaced from 3rd to the last line.
Delete lines from a file:
To delete nth line from newfile.txt
sed 'nd' newfile.txt
To delete the last line.
sed '$d' newfile.txt
To delete a range of lines from p to t
sed 'p,td' newfile.txt
To delete the lines which have the specified pattern.
sed '/pattern/d' newfile.txt
- Understanding ps command
- How to list connections on the server with netstat command
- Understanding top Command
- Useful Postfix commands Linux
- How to use linux screen command
- Useful Exim Commands
- Basic OpenVZ commands
If you like the post Understanding top Command and wish to receive more articles from us, please like our FB page: GrepItOut
Your suggestions and feedbacks will encourage us and help to improve further, please feel free to write your comments. For more details on our services, please drop us an E-mail at firstname.lastname@example.org