sed is a Linux tool called as “Stream Editor“. It is very helpful to search and replace text patterns from the files. A very handy tool for Linux admins and UNIX/Linux developers.
sed can be used to perform many actions on files and text in the files like –
- find a characted and replace in the file
- replace a string
- remove any line or number of lines
- removing or replacing spaces
- there are more actions that can be performed
Example 1 – Replace a word in the file
sed ‘s/2023/2024/g’ filename.text s means substitute 2023 with 2024
sed -i ‘s/2023/2024/g’ filename.text in this command i means insert mode to update the file with change.
Example 2 – Deleting a word from the file –
sed ‘s/2023//g’
Example 3 – find a word in the line and delete it
sed ‘/toberemoved/d’ filename.txt [this will delete the line that match the word toberemoved]
Example 4 – remove the empty lines
sed ‘/^$/d’ filename.txt [^ shows startes with $ means empty and d means delete]
Example 5 – remove tabs
sed -i ‘s/\t/ /g’ filename.text
Example 6 – remove line number 6
sed -i ‘6d’ filename.txt
sed -1 ‘6,7d’ filename.txt
Example 7 – replace except one line
sed ’10!s/2023/2024/s’ filename.text