8.Sed 替换

s

[jerry]$ sed 's/,/ | /' books.txt

替换

On executing the above code, you get the following result:

1) A Storm of Swords | George R. R. Martin, 1216 
2) The Two Towers | J. R. R. Tolkien, 352 
3) The Alchemist | Paulo Coelho, 197 
4) The Fellowship of the Ring | J. R. R. Tolkien, 432 
5) The Pilgrimage | Paulo Coelho, 288 
6) A Game of Thrones | George R. R. Martin, 8

写入文件

[jerry]$ sed -n 's/Paulo Coelho/PAULO COELHO/w junk.txt' books.txt

i

忽略大小写

g

全部替换

So far, we have used only the foreslash(/) character as a delimiter, but we can also use vertical bar(|), at sign(@), caret(^), exclamation mark(!) as a delimiter. The following example shows how to use other characters as a delimiter

除了使用// 作为替换标识符之外 还可以使用 | 操作符 @操作符 ^ 操作符 还有! 操作符

子字符串

使用() 创建子字符集

[jerry]$ echo "Three,One,Two" | sed 's|\(\w\+\),\(\w\+\),\(\w\+\)|\2,\3,\1|'

最好的 方式再加个 -E 不加的话 可能? {} 等特殊符号都要加反斜杠

echo "Three,One,Two" | sed -E 's|(\w+),(\w+),(\w+)|\2,\3,\1|'

dingmac@modern_php$ echo "Three,One,Two" | sed -E 's|(\w+),(\w+),(\w+)|\2,\3,\1|'
Three,One,Two

其他类型的方式

  • \L: When \L is specified in the replacement string, it treats all the remaining characters of the the word after \L as lowercase characters. For example, the characters “ULO” are treated as lowercase characters.

  • \u: When \u is specified in the replacement string, it treats the immediate character after \u as an uppercase character. In the following example, \u is used before the characters ‘a’ and ‘o’. Hence SED treats these characters as uppercase letters.

  • \E: This flag should be used with \L or \U. It stops the conversion initiated by the flag \L or \U. In the following example, only the first word is replaced with uppercase letters.

dingmac@ubuntu:~$ echo "zhangsan"| sed 's/zh/Zh\Ush/'
ZhSHangsan
dingmac@ubuntu:~$ echo "zhangsan"| sed 's/zh/Zh\ush/'
ZhShangsan
dingmac@ubuntu:~$ echo "zhangsan"| sed 's/zh/Zh\Lsh/'
Zhshangsan
dingmac@ubuntu:~$ echo "zhangsan"| sed 's/zh/Zh\LSH/'
Zhshangsan
dingmac@ubuntu:~$ echo "zhangsan"| sed 's/zh/Zh\lSH/'
ZhsHangsan

dingmac@ubuntu:~$ echo "zhangsan"| sed 's/zh/\Uzh\Esa/'
ZHsaangsan

猜你喜欢

转载自blog.csdn.net/successdd/article/details/79078105