本文主要是介绍12. sed 替换 增强版,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
原文 https://www.thegeekstuff.com/2009/09/unix-sed-tutorial-replace-text-inside-a-file-using-substitute-command/?utm_source=sitekickr&utm_medium=snip_button
语法
Syntax:#sed 'ADDRESSs/REGEXP/REPLACEMENT/FLAGS' filename
#sed 'PATTERNs/REGEXP/REPLACEMENT/FLAGS' filename
上面的/是delimiter 就是分隔符 在某些情况可以使用其他分隔符 比如 @,^,| 等
这个某些情况比如 要替换// 替换成 -
重点
敲黑板敲黑板!!!
FLAGS can be any of the following
g Replace all the instance of REGEXP with REPLACEMENT
g 替换一行中所有 REGEXP 的实例 默认情况只匹配第一个 过会看实例n Could be any number,replace nth instance of the REGEXP with REPLACEMENT.
p If substitution was made, then prints the new pattern space.
只替换第n找到的REGEXP 实例i match REGEXP in a case-insensitive manner. 忽略大小写
w file If substitution was made, write out the result to the given file. 将替换好的保存到文件中 记住!!! 只有替换了的 替换了1行 就只存一行 替换了两行就是两行
We can use different delimiters ( one of @ % ; : ) instead of /
但是注意 当使用n 的时候 不能使用g
现在有一个文件
$ cat thegeekstuff.txt
# Instruction Guides
1. Linux Sysadmin, Linux Scripting etc.
2. Databases - Oracle, mySQL etc.
3. Security (Firewall, Network, Online Security etc)
4. Storage in Linux
5. Productivity (Too many technologies to explore, not much time available)
# Additional FAQS
6. Windows- Sysadmin, reboot etc.
做练习
- Substitute Word “Linux” to “Linux-Unix” Using sed s//
$ sed 's/Linux/Linux-Unix/' thegeekstuff.txt
只替换每一行的第一个Linux 变成 Linux-Unix
其余的flag 可以自行测试 :)
补充
我写了下面一个sed 命令
dingmac@modern_php$ sed '/Administration/{ s/Administration/Supervision/;:label ;n;b label; }' theGeekStuff.txt
在MAC 中} 之前一定要记得;
上面的脚本会有报错 报错原因参考如下
https://discussions.apple.com/thread/2098594
sed: 1: "/Administration/{ s/Adm ...": bad flag in substitute command: ':'
原因如下
if you want a shell command line to span multiple lines, then you need to tell the shell that command is not finished when you hit RETURN.
假如在 有shell命令中有跨越多行的命令时 一定要按照下面的写法
sed '{
command1;
command2 # ; 符号可有可无 多个命令一行一定要有
}'
第二点 mac 不支持e 命令 这里是e 命令 不是e参数
#mac
dingmac@modern_php$ echo 'a' | sed 'e date'
sed: 1: "e date": invalid command code e
#Ubuntu
dingmac@ubuntu:~$ echo 'a' | sed -n 'e date'
Wed Jan 17 11:49:38 CST 2018
这篇关于12. sed 替换 增强版的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!