此专题主要包含shell处理方面的技巧,如awk,sed等

1. 格式化文本

(1)有文本(file.txt),格式如下:
ad_click
1477569
1477569

ad_showtimes
1004446
1004446

ad

admin
35
35

想格式化为
ad_click 1477569 1477569
ad_showtimes 1004446 1004446
ad 0 0
admin 35 35

实现:

  1. awk -v RS'{print $1,$2+0,$3+0}' file.txt  
  2. or  
  3. awk -v RS'{print $1,$2?$2:0,$3?$3:0}' file.txt 

(2). 四行合并一行

  1. # cat filename  
  2. 111111111  
  3. 222222222  
  4. 333333333  
  5. 444444444  
  6. 555555555  
  7. 666666666  
  8. 777777777  
  9. 888888888  
  10. 999999999  
  11.  
  12. # awk '{if (NR%4==0){print $0} else {printf"%s ",$0}}' filename  
  13.  
  14. 111111111 222222222 333333333 444444444  
  15. 555555555 666666666 777777777 888888888  
  16. 999999999 
  1. # awk '{if(NR%4!=0)ORS=" ";else ORS="\n";print}' filename
  2. or  
  3. # awk '{if(NR%4==0)ORS="\n";else ORS=" ";print}' filename

(3)一个文本:
2006
中国
四川
042834 1 2 3
042835 4 5 6
042836 7 8 9
2007
中国
重庆
042837 1 2 3
042838 4 5 6
042839 7 8 9
......
......
要合并为
042834 1 2 3 2006 中国 四川
042835 4 5 6 2006 中国 四川
042836 7 8 9 2006 中国 四川
042837 1 2 3 2007 中国 重庆
042838 4 5 6 2007 中国 重庆
042839 7 8 9 2007 中国 重庆

脚本如下:

  1. #!/bin/bash  
  2. #########################################################################  
  3. # Author: pchuang@cn.ibm.com  
  4. # Created Time: Sun 05 Apr 2009 10:04:51 AM CST  
  5. # File Name: process.sh  
  6. # Description: A script for the processing of the TEXT   
  7. #########################################################################  
  8.  
  9. file=$1  
  10. i=1 
  11. lines[0]=""  
  12. if [ ! -s $1 ] ; then  
  13. echo "Please specify a valid text file"  
  14. exit 1  
  15. fi  
  16.  
  17. while read line  
  18. do  
  19. lines[$i]="$line"  
  20. if [ $i -eq 6 ] ; then  
  21. lines[$i]="$line"  
  22. for j in $(seq 4 6); do  
  23. echo ${lines[$j]} ${lines[1]} ${lines[2]} ${lines[3]} >> result.txt  
  24. done  
  25. let i=0 
  26. fi  
  27. let i=$i+1  
  28. done < $1 

执行:
$./process.sh text
$more result.txt

042834 1 2 3 2006 中国 四川
042835 4 5 6 2006 中国 四川
042836 7 8 9 2006 中国 四川
042837 1 2 3 2007 中国 重庆
042838 4 5 6 2007 中国 重庆
042839 7 8 9 2007 中国 重庆

后来某牛人用AWK也完成了:

  1. awk 'BEGIN{i=0}{if(NF!=4){h[i++]=$0;next}else{i=0;print $0" "h[0]" "h[1]" "h[2]}}' filename
  1. sed -n "/^[0-9]\+$/h;/^[^ 0-9]\+$/H;/ /{G;s/\n/ /g;p}" filename 

(4) 两列合并成八列
111     111
222     222
333     333
444     444
555     555
666     666
777     777
888     888
999     999
101     101
实现:

  1. # xargs -n8 < filename 
  2. 111 111 222 222 333 333 444 444  
  3. 555 555 666 666 777 777 888 888  
  4. 999 999 101 101 
此文章由 flyinweb 于 2010-05-26 14:52:19 编辑

本日志由 flyinweb 于 2010-05-26 11:15:40 发表,目前已经被浏览 4200 次,评论 0 次;

作者添加了以下标签: sedawkshell

引用通告:http://www.517sou.net/Article/450/Trackback.ashx

评论订阅:http://www.517sou.net/Article/450/Feeds.ashx

评论列表

    暂时没有评论
(必填)
(必填,不会被公开)