Linux SED Command with example
SED Command :
- SED is a powerful text stream editor. Can do insertion, deletion, search and replace (substitution).
- SED command in UNIX supports regular expression which allows it perform complex pattern matching.
sed OPTIONS... [SCRIPT] [INPUTFILE...]
$cat > geekfile.txt
UNIX is great os. unix is opensource. unix is free os. learn operating system. unix linux which one you choose. unix is easy to learn. Unix is a multiuser os. Learn unix .unix is a powerful.
Replacing or substituting string
By default sed replaces the first occurrence of pattern in each line and it won’t affect the 2nd and 3rd …
Here ‘s’ is the substitution variable and ‘/’ are delimiters. The ‘unix’ is the search pattern and ‘linux’ is the replacement string.
Replacing the nth occurrence of a pattern in a line
The above command will replace the second occurrence in each line.
Replacing all the occurrence of the pattern in a line
Use /g (global) with sed command.
Replacing from nth occurrence to all occurrences in a line
Parenthesize first character of each word:
This sed command prints the first character of every word in parenthesis.
Replacing string on a specific line number
It will replace the occurrence at third line.
Duplicating the replaced line with /p flag
/p print flag prints the replaced line twice on the terminal. If a line does not have the search pattern and is not replaced, then the /p prints that line only once.
Printing only the replaced lines
Use the -n option along with the /p print flag to display only the replaced lines. Here the -n option suppresses the duplicate rows generated by the /p flag and prints the replaced lines only one time.
Replacing string on a range of lines
You can specify a range of line numbers to the sed command for replacing a string.
Learn about AWK Command with Example.