Sed command…

Sed is a Stream Editor used for modifying the files in unix (or linux). We can use this command while making some changes like replacing text in a file.

I had here saved a file named file.txt with data

unix is great os. unix is opensource. unix is free os.
learn operating system.
unix linux which one you choose.

Examples:

  1. Replacing or Substituting string
sed 's/unix/linux/' file.txt
It will give output:
linux is great os. unix is opensource. unix is free os.
learn operating system.
linux linux which one you choose.
 "s" specifies the substitution operation. The "/" are delimiters. 
The "unix" is the search pattern and the "linux" is the replacement string.

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.

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.
sed 's/unix/linux/2' file.txt
 Its output: unix is great os. linux is opensource. unix is free os.
learn operating system.
unix linux which one you choose.
The above command replaces the second occurrence of the word "unix"
 with "linux" in a line.

3. Replacing all the occurence of a 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/unix/linux/g' file.txt

4. Replacing from nth occurrence to all occurrences in a line
sed 's/unix/linux/3g' file.txt
Its output: unix is great os. unix is opensource. linux is free os.
learn operating system.
unix linux which one you choose.

5. Double the word
sed 's/\(unix\)/\1\1/' file.txt
It replace the word "unix" in a line with twice as the word like "unixunix" 

6. Duplicating the replaced line with /p flag
The /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.
sed 's/unix/linux/p' file.txt

Note:
How to make permanent changes in file?
sed -i 's/o/X/g' file.txt
It will replace all the 'o' in the file with 'X'
7. Creating backup of a file
sed -i.bak 's/o/X/g' file.txt
Screenshot from 2016-04-05 22-20-51

Stay tuned . . .
Thanks :)

One thought on “Sed command…

  1. Pingback: Daily Dose!

Leave a comment