sed,awk,grep使用小结

来源:互联网 发布:编程难么 编辑:程序博客网 时间:2024/05/16 17:48

$ more t1.sh

#!/bin/sh

#fffff

helloworld ()

{

echo "test ffffff"

}

hellowworld

echo1 xxx ccc

 

1.       查找以echo1开头的行 并获得行号

$ sed -n '/^echo1/=' t1.sh

8

$ grep -n '^echo1' t1.sh | cut -d ':' -f 1

8

$ awk '{if($0 ~ /^echo1/) print FNR}' t1.sh

8

2.       获得文件的行数

$ awk 'END{print NR}' t1.sh

8

$ sed -n '$=' t1.sh

8

$ grep -c "" t1.sh

8

3.       查找包含test并且后面为空格的行并输出

$ grep  'test /+' t1.sh

echo "test ffffff"

$ sed -n '/test /+/p' t1.sh

echo "test ffffff"

$ awk '{if($0 ~ /.*test +/) print $0}' t1.sh

echo "test ffffff"

 

sed命令参数连用 输入结果和行号

$ sed -n -e '/test /+/p' -e '/test /+/=' t1.sh

echo "test ffffff"

5

 

4.        Sed删除指定行

  删除第一行

$ sed '1d' t1.sh

#fffff

helloworld ()

{

echo "test ffffff"

}

hellowworld

echo1 xxx ccc

 

如果要改变t1.sh的内容不能直接将结果定向到t1.sh,否则会将t1.sh至空。

这里1d 1p ,1,2p,$p用法是一样的