想說簡單分析一下 squid 產生的 logs ,於是就想到用 bash 與 awk ,不過,過程不是很順利,發現一些 script 使用上的問題,給他筆記一下。
#!/bin/sh touch /tmp/access.log echo "=== CASE 1 ===" cmd="awk \"BEGIN{a=1;b=2;}{}END{}\" /tmp/access.log" echo echo $cmd echo dd=`$cmd` | === CASE 1 === awk "BEGIN{a=1;b=2;}{}END{}" /tmp/access.log |
#!/bin/sh touch /tmp/access.log echo "=== CASE 2 ===" cmd="awk 'BEGIN{a=1;b=2;}{}END{}' /tmp/access.log" echo echo $cmd echo dd=`$cmd` | === CASE 2 === awk 'BEGIN{a=1;b=2;}{}END{}' /tmp/access.log awk: syntax error at source line 1 context is >>> ' <<< awk: bailing out at source line 1 |
#!/bin/sh touch /tmp/access.log echo "=== CASE 3 ===" cmd="awk 'BEGIN{\ a=1;\ b=2;\ }{}END{}' /tmp/access.log" echo echo $cmd echo dd=`$cmd` | === CASE 3 === awk 'BEGIN{ a=1; b=2;}{}END{}' /tmp/access.log awk: syntax error at source line 1 context is >>> ' <<< missing } awk: bailing out at source line 1 |
#!/bin/sh touch /tmp/access.log echo "=== CASE 4 ===" cmd="awk \"BEGIN{\ a=1;\ b=2;\ }{}END{}\" /tmp/access.log" echo echo $cmd echo dd=`$cmd` | === CASE 4=== awk "BEGIN{ a=1; b=2;}{}END{}" /tmp/access.log awk: non-terminated string BEGIN{... at source line 1 context is >>> <<< awk: giving up source line number 2 |
#!/bin/sh touch /tmp/access.log echo "=== CASE 5 ===" cmd="awk \"BEGIN{\ a=1;\ b=2;\ }{}END{}\" /tmp/access.log" echo echo $cmd echo dd=`$cmd` | === CASE 5=== awk "BEGIN{a=1;b=2;}{}END{}" /tmp/access.log |
簡述一下,在 bash script 使用中,對於 awk 內部的敘述部分,要改用雙引號 " 而不是用單引號 ' ,另外則是敘述句裡頭不能有空白或Tab等。所以搞到最後我就改用 profile 的方式:
#!/bin/sh
touch /tmp/access.log
touch /tmp/awk.profile
awk_profile="BEGIN { \
a=1;\
b=2;\
}{}END{}"
echo $awk_profile > /tmp/awk.profile
cmd_out=`awk -f /tmp/awk.profile /tmp/access.log`
沒有留言:
張貼留言