Monday, July 30, 2018

Sed command examples

1. Viewing a range of lines from a file
#sed -n '5,10p' filename

2. Viewing an entire file except few lines
#sed '5,10d' filename

3. Viewing non-consecutive range of lines from a file
#sed -n -e '5,10p' -e '15,20p' filename

4. Replacing specific word in a file
# sed 's/this/that/g' filename

5. Replacing specific word ignoring character case from a file.
# sed 's/this/that/gi' filename

6. Replace multiple blank space with single blank space.
# sed 's/ *//g' filename
# ip route show | sed 's/  */ /g'

7. Replacing words in a range of lines in a file
# sed '5,10 s/this/that/g' filename

8. Viewing the configuration files without the comments and blank lines.
# sed '/^#\|^$\| *#/d' httpd.conf

9. Substitution of words using regular expression.
# sed 's/[Tt]his/that/g' filename

10. Viewing lines using a given pattern
# sed -n '/^Jul 1/ p' /var/log/secure

11. Inserting spaces in a file
# sed G filename
# sed "G;G" filename

12.  dos2unix using sed
# sed -i 's/\r//' filename

13. In-place editing and backup of original file
# sed -i'.orig' 's/this/that/g' filename

14. Switching pair of words
# sed 's/^\(.*\),\(.*\)$/\2\, \1/g' filename

15. Replacing word only if a separate match is found.
# sed '/services/ s/start/stop/g' filename

16. Performing 2 more substitution on a file
# sed -i 's/this/that/g;s/there/their/gi' filename

17. Combining sed and other commands.
# ip route show | sed -n '/src/p' | sed -e 's/  */ /g' | cut -d' ' -f9

No comments: