Linux sed 命令

2017-07-14|Categories: External cmd|





<b>This</b> is what <span style="text-decoration: underline;">I</span> meant. Understand?


$ sed 's/<.*>//g' html.txt
 meant. Understand?


$ sed 's/<[^>]*>//g' html.txt
This is what I meant. Understand?


What if, in sed, you have lots of slashes in the pattern and/or replacement?

One solution is to escape them all (the so-called sawtooth effect):

sed 's/\/a\/b\/c\//\/d\/e\/f\//'    # change "a/b/c/" to "d/e/f/"

but that is ugly and unreadable. It's a not-so-known fact that sed can use ANY character as separator for the "s" command. Basically, sed takes whatever follows the "s" as the separator. So, our code above can be rewritten for example in one of the following ways:

sed 's_/a/b/c/_/d/e/f/_'
sed 's;/a/b/c/;/d/e/f/;'
sed 's#/a/b/c/#/d/e/f/#'
sed 's|/a/b/c/|/d/e/f/|'
sed 's /a/b/c/ /d/e/f/ '       # yes, even space
# etc.

An even less-known fact is that you can use a different delimiter even for patterns used in addresses, using a special syntax:

# do this (ugly)...
sed '/\/a\/b\/c\//{do something;}'
# ...or these (better)
sed '\#/a/b/c/#{do something;}'
sed '\_/a/b/c/_{do something;}'
sed '\%/a/b/c/%{do something;}'
# etc.

Leave A Comment