sed
-i 替换并保存
's/pattern/replace_string/' 只替换第一处
's/pattern/replace_string/g' 替换所有
's/pattern/replace_string/Ng' 从第N处开始匹配
# ex 直接替换文本
[clz@localhost shell_learn]$ sed -i 's/cecho.sh/xxxxxxxxxxxxxx/' file_sum.md5
sed
# 移除空白行
sed 's/\b[0-9]\{3\}\b/NUMBER/g' file
匹配两位数字 \b为边界
匹配每一个单词
[clz@localhost shell_learn]$ echo this is an example | sed 's/\w\+/[&]/g'
[this] [is] [an] [example]
子串匹配
第一条命令将digit 替换为 7。样式中匹配到的子串是7. \(pattern\)
用于匹配子串。模式被包括在使用斜线转义过的()中。对于匹配到的第一个子串, 其对应的标记是\1, 匹配到的第二个子串是\2, 往后依次类推。
# ex 1
[clz@localhost ~]$ echo this is digit 7 in a number | sed 's/digit \([0-9]\)/\1/'
this is 7 in a number
# ex 2 将两个匹配到的字符串交换
[clz@localhost ~]$ echo seven EIGHT | sed 's/\([a-z]\+\) \([A-Z]\+\)/\2 \1/'
EIGHT seven
引用
sed表达式通常用单引号来引用。也可以用双引号,通过对表达式求职进行扩展。
text=hello
echo hello world | sed "s/$text/HELLO/"
HELLO world