例如在文件1.log中 id=1 a=1,b=2,c=3,d=4,e=5....,z=100
id=2 a=3,b=4,d=20,e=6,f=7,...,z=30
id=3 a=4,b=4,c=2,d=5,e=8,...,z=29
.... 现在我想统计在log中d的分布~ 有什么好方法吗? grep每次都是输出整行,没法提取一个关键词的信息。
人生最曼妙的风景,竟是内心的淡定与从容!
awk的解法:
#!/bin/bash awk -F"," ' NF == 0 {next} # skip blank line NF == 1 {printf "%s ", } # for id line # for data line { for (i = 1; i <= NF; i++) { split($i, a, "="); if (a[1] == "d") print $i; } } ' 1.log
結果如下: id=1 d=4 id=2 d=20 id=3 d=5
awk的好處在於可以對輸入/輸出的格式作比較精細的處理。
先去掉id=中的d=, 然後 grep -o 參數 提取匹配的模式。 再把數字再抓出來, awk或者cut就可以了。
grep -v "id=[0-9]*" 1.log | grep -o "d=[0-9]*" | awk -F'=' '{ print }'
或者, 用egrep,
grep -v "id=[0-9]*" 1.log | egrep -o "d=[0-9]+" | cut -d '=' -f 2
方法還是多啦, 其他sed那些 都可以用;
給個其他思路...
mv 1.log /opt/www/1.log
然後用php腳本來處理,新建一個1.php.腳本如下:
<?php $str = file_get_contents("1.log"); $arr = explode(",",$str); foreach($arr as $k=>$v){ $b = explode("=",$v); if($b[0]=="d"){ $new_arr[] = $b[1]; } } print_r($new_arr); ?>
這個比較適合用 awk 或者 flex 來做。
flex:
$ cat 1.l %% d=[0-9]*, printf("%d\n", atoi(yytext + 2)); .|\n $ flex 1.l && gcc lex.yy.c -lfl && ./a.out < 1.txt 4 20 5
這種 log 處理 awk、perl、ruby 都行。上個 perl 版
perl -ne 'print if m/d=(\d+)/' your_log_file
用Python吧,什麼OS下麵都很好用。
import re _re.compile('d=\d+') # readline in 'line' matched = _re.search(line) if matched: extracted = matched.group(0) print extracted
用cut命令吧。 cut -d '分割字符' -f '選取第幾段的意思' 好像還有個參數 -c。
$ cat 1.log |cut -c 0-4 |cut -d ',' -f 4
可以自己man 一下。
awk的解法:
結果如下:
id=1 d=4
id=2 d=20
id=3 d=5
awk的好處在於可以對輸入/輸出的格式作比較精細的處理。
先去掉id=中的d=, 然後
grep -o 參數 提取匹配的模式。 再把數字再抓出來, awk或者cut就可以了。
或者, 用egrep,
方法還是多啦, 其他sed那些 都可以用;
給個其他思路...
mv 1.log /opt/www/1.log
然後用php腳本來處理,新建一個1.php.腳本如下:
這個比較適合用 awk 或者 flex 來做。
flex:
這種 log 處理 awk、perl、ruby 都行。上個 perl 版
用Python吧,什麼OS下麵都很好用。
用cut命令吧。
cut -d '分割字符' -f '選取第幾段的意思'
好像還有個參數 -c。
可以自己man 一下。