是五月呀!

shell中的sed

用s命令替换

1
2
3
4
5
6
7
8
9
$ cat pets.txt
This is my cat
my cat's name is betty
This is my dog
my dog's name is frank
This is my fish
my fish's name is george
This is my goat
my goat's name is adam

把其中的my字符串替换成Hao Chen’s,下面的语句应该很好理解(s表示替换命令,/my/表示匹配my,/Hao Chen’s/表示把匹配替换成Hao Chen’s,/g 表示一行上的替换所有的匹配):

1
2
3
4
5
6
7
8
9
$ sed "s/my/Hao Chen's/g" pets.txt
This is Hao Chen's cat
Hao Chen's cat's name is betty
This is Hao Chen's dog
Hao Chen's dog's name is frank
This is Hao Chen's fish
Hao Chen's fish's name is george
This is Hao Chen's goat
Hao Chen's goat's name is adam

注意,如果替换命令中有单引号',那外层就别用单引号了,否则转义也不好使。

再注意:上面的sed并没有对文件的内容改变,只是把处理过后的内容输出,如果你要写回文件,你可以使用重定向,如:

1
$ sed "s/my/Hao Chen's/g" pets.txt > hao_pets.txt

或使用 -i 参数直接修改文件内容:

1
$ sed -i "s/my/Hao Chen's/g" pets.txt

在每一行最前面加点东西:

1
2
3
4
5
6
7
8
9
$ sed 's/^/#/g' pets.txt
#This is my cat
# my cat's name is betty
#This is my dog
# my dog's name is frank
#This is my fish
# my fish's name is george
#This is my goat
# my goat's name is adam

在每一行最后面加点东西:

1
2
3
4
5
6
7
8
9
$ sed 's/$/ --- /g' pets.txt
This is my cat ---
my cat's name is betty ---
This is my dog ---
my dog's name is frank ---
This is my fish ---
my fish's name is george ---
This is my goat ---
my goat's name is adam ---

不包含abc的行,将其中的123改成456

1
sed '/abc/!s/123/456/g' fileName

只替换第3行:

1
sed "3s/my/your/g" pets.txt

只替换第3到第6行:

1
sed "3,6s/my/your/g" pets.txt

只替换每一行的第一个s:

1
sed 's/s/S/1' my.txt

顺手介绍一下正则表达式的一些最基本的东西:

  • ^表示一行的开头。如:/^#/#开头的匹配。
  • $表示一行的结尾。如:/}$/}结尾的匹配。
  • \<表示词首。 如:\<abc表示以abc为首的詞。
  • \>表示词尾。 如:abc\>表示以abc結尾的詞。
  • .表示任何单个字符。
  • *表示某个字符出现了0次或多次。
  • [ ]字符集合。 如:[abc]表示匹配a或b或c,还有[a-zA-Z]表示匹配所有的26个字符。如果其中有^表示反,如[^a]表示非a的字符。

多个匹配

如果我们需要一次替换多个模式,可参看下面的示例:(第一个模式把第一行到第三行的my替换成your,第二个则把第3行以后的This替换成了That)

1
$ sed '1,3s/my/your/g; 3,$s/This/That/g' my.txt

上面的命令等价于:(注:下面使用的是sed的-e命令行参数)

1
sed -e '1,3s/my/your/g' -e '3,$s/This/That/g' my.txt

我们可以使用&来当做被匹配的变量,然后可以在左右加点东西。如下所示:

1
2
3
4
5
$ sed 's/my/[&]/g' my.txt
This is [my] cat, [my] cat's name is betty
This is [my] dog, [my] dog's name is frank
This is [my] fish, [my] fish's name is george
This is [my] goat, [my] goat's name is adam

圆括号匹配

使用圆括号匹配的示例:(圆括号括起来的正则表达式所匹配的字符串会可以当成变量来使用,sed中使用的是\1,\2…)

1
2
3
4
5
$ sed 's/This is my \([^,&]*\),.*is \(.*\)/\1:\2/g' my.txt
cat:betty
dog:frank
fish:george
goat:adam

上面这个例子中的正则表达式有点复杂,解开如下(去掉转义字符):

正则为:This is my ([^,]*),.*is (.*)
匹配为:This is my (cat),……….is (betty)
然后:\1就是cat,\2就是betty。

参考:
SED 简明教程