8.Sed 替换

12 篇文章 0 订阅

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值