Friday, 3 August 2018

Linux: sed - Replace / Substitution command

Command to replace the keyword unix with linux in sample.txt file.
sed 's/unix/linux/' sample.txt 

Output: Sample file for learning SED command in linux. As we know unix is an free os.
Explanation of above SED command:
‘s’ is used to replace keyword where the above keyword is used to replace the unix keyword in the first occurrence only.
  
 Command to replace all the occurrence of unix keyword in sample.txt file.


sed 's/unix/linux/g' sample.txt 

Output: Sample file for learning SED command in linux. As we know linux is an free os

Explanation of above SED command:
‘g’ is used to replace keyword globally (i.e) it is used to replace all the occurrence of the keyword in a file.
            Command to replace 2nd occurrence of a string
 sed 's/linux/solaris/2' sample.txt

Output: Sample file for learning SED command in unix. As we know unix is an free os
linux is also free os and solaris is also free source.
Explanation of above SED command:
‘2’ is used to replace second in the second occurrence in a file.

Note: ‘2’ can be replace with ‘n’ to replace any occurrence. In our example I took ‘2’ for second second replacement.

Replace every occurrence of Nick with John in report.txt
sed 's/Nick/John/g' report.txt

Replace every occurrence of Nick or nick with John.
sed 's/Nick|nick/John/g' report.txt

Replace ham with cheese in file.txt except in the 5th line
sed '5!s/ham/cheese/' file.txt

Unless boom is found replace aaa with bb
sed '/boom/!s/aaa/bb/' file.txt

Replaces one with unos in a case-insensitive manner, so it will print "unos TWO"
echo ONE TWO | sed "s/one/unos/I"

Replace foo with bar only for the first instance in a line.
sed 's/foo/bar/' file.txt

Replace foo with bar only for the 4th instance in a line.
sed 's/foo/bar/4' file.txt

Replace foo with bar for all instances in a line.
sed 's/foo/bar/g' file.txt


Do replacement of Johnson with White only on lines between 1 and 20
sed '1,20 s/Johnson/White/g' file.txt

The above reversed (match all except lines 1-20)
sed '1,20 !s/Johnson/White/g' file.txt

Replace only between "from" and "until"
sed '/from/,/until/ { s/\<red\>/magenta/g; \ s/\<blue\>/cyan/g; }' file.txt

Replace only from the word "ENDNOTES:" until EOF
sed '/ENDNOTES:/,$ { s/Schaff/Herzog/g; \s/Kraft/Ebbing/g; }' file.txt





0 comments:

Post a Comment