grep
-E
使用正则: echo this is a line. | grep -E "[a-z]\."
-o
只输出匹配到的文本-v
除匹配到的所有行-c
匹配的行数,匹配数:echo -e "this is a word.\n next line." | egrep -o "[a-z]\." | wc -l
-n
匹配到在第几行-b -o
位于改行的第几个开始字符-l
搜索多个文件,匹配搜索到的文件,-L
取反,文件中匹配不到的。
-
-R
递归搜索文件:grep "text" . -R -n
-i
忽略大小写:grep -i Liunx sample.txt
-e
匹配多个样式:grep -e not -e linux sample*
.-f
输入多个匹配样式的文件-Z
使用\0
分隔,删除匹配的文件grep "test" file* -lZ | xargs -0 rm
-A
(After)匹配结果之后的行-B
(Before)匹配结果之前的多少行-C
结果前后的几行
cut
- 获取1,3列:
cut -f1,3 student_data.txt
--complement
:取反列-d
指定定界符,echo a,b,c,d | cut -f2 -d","
-c
第几个到第几个字符,cut -c1-5 student_data.txt
sed
- 移除文件的空白行
sed '/^$/d' file1
- 已匹配标记&:
sed 's/\w\+/[&]' file1
,匹配单词,标记为[word]. - 子串匹配标记\1:
echo seven EIGHT | sed 's/\([a-z]\+\) \([A-Z]\+\)/\2 \1/'
- 双引号求值:
test=hello;echo hello world | sed "s/$text/HELLO/"
-i
修改替换原文件
- 对js文件进行压缩:
catsample.js | tr -d '\n\t' | tr -s ' ' | sed 's:/\*.*\*/::g' | sed 's/ \?\([{}();,:]\) \?/\1/g '
awk
循环处理文件的每一行
- 特殊变量:
$0
当前行,$1
当前行第一个字段的内容,NR
当前行号,NF
当前行的字段数。seq 5 | awk 'BEGIN{ sum=0;print "Summation:"} {print $1"+"; sum+=$1 } END{ print "=="; print sum }'
- getline读取行
some用例
- 迭代行、单词和字符
while read line; do for word in $line; do for((i=0;i<${#word};i++)) do echo ${word:i:1} ; done ; done; done < file1
,${#word}
返回word的长度。 - paste按列合并文件,
-d
指定定界符,paste file1.txt file2.txt -d ","
- 文件的第几列,
ls -l | awk '{ print $1 " : " $9 }'
- 文件的第几行到第几行:
awk 'Nr==3,NR=7' file1.txt
- 匹配之间的行,以start的行到end之间的行,
awk '/start/, /end/' file1
- 反转,反正句中的所有单词:
echo "this is line." | rev | tr ' ' '\n' | tac | tr '\n' ' ' | rev
- 逆序打印行,
seq 9 | tac
(cat => tac),使用awk:seq 9 | awk { lifo[NR]=$0; lno=NR} END{ for(;lno>-1;lno--){ print lifo[lno]; } }
- 匹配电子邮箱地址,
egrep -o '[A-Za-z0-9.]+@[A-Za-z0-9.]+\.[a-zA-Z]{2,4}' url_email.txt
- 匹配URL,
egrep -o "http://[a-zA-Z0-9.]+\.[a-zA-Z]{2,3}" url_email.txt
- 移除包含某单词的句子,
echo this line. this is gun, is so fun. this is bash. | sed 's/ [^.]*so fun[^.]*\.//g'
- awk实现head,
awk 'NR <=10' file1
- awk实现tail,
awk '{ buffer[NR % 10] = $0; } END { for(i=1;i<11;i++) { print buffer[i%10] } } ' paste.txt
,$0
当前行的文本。 - awk实现tac,
awk '{ buffer[NR] = $0; } END { for(i=NR; i>0; i--) { print buffer[i] } }' file1
- 文本替换,
var="this is a line of text"; echo ${var/line/LINE}
,文本切片,string="asdfepklcjda"; echo ${string:4:9}
Linux Shell Scripting Cookbook