sed 命令
将 /etc/passwd 的内容列出并且列印行号,同时,请将第 2~5 行删除!
nl /etc/passwd | sed '2,5d'
要删除第 3 到最后一行
nl /etc/passwd | sed '3,$d'
在第二行后(亦即是加在第三行)加上『drink tea?』字样!
nl /etc/passwd | sed '2a drink tea'
如果是要增加两行以上,在第二行后面加入两行字,例如『Drink tea or .....』与『drink beer?』
nl /etc/passwd | sed '2a Drink tea or ......\ > drink beer ?'
将第2-5行的内容取代成为『No 2-5 number』呢?
nl /etc/passwd | sed '2,5c No 2-5 number'
仅列出 /etc/passwd 文件内的第 5-7 行
nl /etc/passwd | sed -n '5,7p'
搜索 /etc/passwd有root关键字的行
nl /etc/passwd | sed '/root/p'
使用-n的时候将只打印包含模板的行。
nl /etc/passwd | sed -n '/root/p'
删除/etc/passwd所有包含root的行,其他行输出
nl /etc/passwd | sed '/root/d'
搜索/etc/passwd,找到root对应的行,执行后面花括号中的一组命令,每个命令之间用分号分隔,这里把bash替换为blueshell,再输出这行:
nl /etc/passwd | sed -n '/root/{s/bash/blueshell/;p}'
如果只替换/etc/passwd的第一个bash关键字为blueshell,就退出
nl /etc/passwd | sed -n '/bash/{s/bash/blueshell/;p;q}'
除了整行的处理模式之外, sed 还可以用行为单位进行部分数据的搜寻并取代。基本上 sed 的搜寻与替代的与 vi 相当的类似!他有点像这样:
sed 's/要被取代的字串/新的字串/g'
将 IP 前面的部分予以删除
/sbin/ifconfig eth0 | grep 'inet addr' | sed 's/^.*addr://g'
将 IP 后面的部分予以删除
/sbin/ifconfig eth0 | grep 'inet addr' | sed 's/^.*addr://g' | sed 's/Bcast.*$//g'
一条sed命令,删除/etc/passwd第三行到末尾的数据,并把bash替换为blueshell
nl /etc/passwd | sed -e '3,$d' -e 's/bash/blueshell/'
-e表示多点编辑,第一个编辑命令删除/etc/passwd第三行到末尾的数据,第二条命令搜索bash替换为blueshell。
利用 sed 将 regular_express.txt 内每一行结尾若为 . 则换成 !
sed -i 's/\.$/\!/g' regular_express.txt
利用 sed 直接在 regular_express.txt 最后一行加入『# This is a test』
sed -i '$a # This is a test' regular_express.txt
sed 的『 -i 』选项可以直接修改文件内容,这功能非常有帮助!举例来说,如果你有一个 100 万行的文件,你要在第 100 行加某些文字,此时使用 vim 可能会疯掉!因为文件太大了!那怎办?就利用 sed 啊!透过 sed 直接修改/取代的功能,你甚至不需要使用 vim 去修订!
#读取第190~196行数据
#sed -n '190,196p' test.txt #sed -n '190,6p' test.txt
#读取大于800M的文件的详细信息
# find / -type f -size +800M -print0 | xargs -0 ls -l -h # find / -type f -size +8k -print0 | xargs -0 du -h
# 查找linux下的大目录
# du -h / --max-depth=1 #find / -name "*.txt" -exec ls -l "{}" \; # grep -Rn "macth" txt # grep -o "match" txt

浙公网安备 33010602011771号