首页 > 代码库 > sed 命令运用
sed 命令运用
sed 命令:
echo "I am oldboy,my qq is 1234567" >>oldboy.txt
要求:
1、取出oldboy.txt 文件中的oldboy字符串
方法一:
[root@git oldboy]# echo "I am oldboy,my qq is 1234567">oldboy.txt
[root@git oldboy]# cat oldboy.txt
I am oldboy,my qq is 1234567
[root@git oldboy]# sed ‘s#^.*m ##g‘ oldboy.txt
oldboy,my qq is 1234567
[root@git oldboy]# sed ‘s#^.*m ##g‘ oldboy.txt |sed ‘s#,.*##g‘
oldboy
[root@git oldboy]# sed ‘s/^.*m //g‘ oldboy.txt|sed ‘s/,.*//g‘
oldboy
注意:"#"和"/"都是替换的符号
方法二:
[root@git oldboy]# sed ‘s#^.*m \(oldboy\),.*#\1#g‘ oldboy.txt
oldboy
[root@git oldboy]# sed ‘s#^.*m \(old\)\(boy\),.*#\1#g‘ oldboy.txt
old
[root@git oldboy]# sed ‘s#^.*m \(old\)\(boy\),.*#\1\2#g‘ oldboy.txt
oldboy
[root@git oldboy]# sed ‘s#^.*m \(old\)\(boy\),.*#\2#g‘ oldboy.txt
boy
\ 后面加数字的意思是取出前面括号里面的内容,第一个括号表示1,第二个表示2,以此类推。
要求:
[root@git oldboy]# cat oldboy.txt
I am oldboy,my qq is 1234567
I am old,but am strong
welcome to test
去除oldboy.txt中含old不含oldboy的行
方法一:
[root@git oldboy]# sed ‘/old[^boy]/d‘ oldboy.txt
I am oldboy,my qq is 1234567
welcome to test
方法二:
[root@git oldboy]# sed ‘/\<old\>/d‘ oldboy.txt
I am oldboy,my qq is 1234567
welcome to test
"<>"匹配单个字符
将old不含boy的行替换为www.baidu.com
[root@git oldboy]# sed ‘s#old[^boy]#www.baidu.com#g‘ oldboy.txt
I am oldboy,my qq is 1234567
I am www.baidu.combut am strong
welcome to test
[root@git oldboy]# sed ‘s#\<old\>#www.baidu.com#g‘ oldboy.txt
I am oldboy,my qq is 1234567
I am www.baidu.com,but am strong
welcome to test
sed 命令运用