awk和sed的一些小功能集合

一、awk动态print
■例子:
有文件out.txt,内容如下:
---------------
LEVEL0,LEVEL1,LEVEL2,LEVEL3,LEVEL4,LEVEL5
one,two,three,four,five,six
---------------
以下语句,根据输入的数字,动态输出值:
cat $out|awk -v col_number="${num}" 'BEGIN {FS=","} {print $col_number}'
注:num是动态输入的值

二、sed删除行
■例子:
删除文件的前两行:
cat $out |sed '1,2d'

三、awk删除第一列和最后一列
■例子:
有文件out.txt,内容如下:
---------------
LEVEL0,LEVEL1,LEVEL2,LEVEL3,LEVEL4,LEVEL5
one,two,three,four,five,six
---------------
以下语句执行后输出结果为:
cat out.txt |awk -F, '{a=$2;for(i=3;i<NF;i++)a=a FS $i;print a}'

---------------
LEVEL1,LEVEL2,LEVEL3,LEVEL4
two,three,four,five
---------------

四、awk合并两个文件的列
■例子:
有文件1.txt 内容如下:
-------------
1
1
1
-------------
有文件2.txt 内容如下:
-------------
2 3
2 3
2 3
-------------
以下语句执行后可把两个文件的列合并:
awk 'NR==FNR{a[i]=$0;i++}NR>FNR{print a[j]" "$0;j++}' 1.txt 2.txt >3.txt
输出结果为:
--------------
1 2 3
1 2 3
1 2 3
--------------

五、sed替换斜杠为反斜杠
echo "2016\04\28" |sed 's#\\#/#g'
结果为:2016/04/28
echo "2016/04/28" |sed 's#/#\\#g'
结果为:2016\04\28

猜你喜欢

转载自zhangch-fnst.iteye.com/blog/2286302
今日推荐