2011-10-11 42 views
0

如何將參數傳遞給awk以將字符串與管道輸入進行比較? 例如,下面是使用特定的文件夾如何在awk中通過bash和字符串比較傳遞參數?

#!/bin/bash 
$FILTER_DIR=$1 

# file date before it should be listed. 
FILTER_BEFORE="2011-08" 

# $6 in awk statement is date of file name($8) 
find $1 -type f | \ 
    sed 's/^/ls -l /g' | \ 
    sh | \ 
    awk ' if ($6 le $FILTER_BEFORE) { print $8 }' 

結果列表下的$ FILER_DIR所有文件,無需過濾下篩選2011年8月之前創建的文件。 看來AWK沒有正確地從bash接收$ FILTER_BEFORE。 任何意見是讚賞!

+0

'le'是Perl中,不AWK:'AWK -v 「FB = $ FILTER_BEFORE」 '$ 6 <= FB {打印$ 8}'' –

回答

2

您將需要使用雙引號並轉義其他AWK變量,以便它們不會被bash解釋。

find $1 -type f | \ 
    sed 's/^/ls -l /g' | \ 
    sh | \ 
    awk " if (\$6 le \"$FILTER_BEFORE\") { print \$8 }" 

或者,您可以將變量分解爲雙引號,以避免轉義。

find $1 -type f | \ 
    sed 's/^/ls -l /g' | \ 
    sh | \ 
    awk ' if ($6 le "'"$FILTER_BEFORE"'") { print $8 }' 
4

如果使用GAWK,把它作爲一個參數

find $1 -type f | 
sed 's/^/ls -l /g' | 
sh | 
awk -v filter_before=${FILTER_BEFORE} '{ if ($6 <= filter_before) { print $8 } }' 
+0

我根本不知道該功能。壯觀! –

+1

+1。但是,對於以管道結尾的行來說,不需要反斜線換行符。 –

1

我會去用:

touch -t 201107302359 30_july_2011 
find . -type f ! -newer 30_july_2011 

還是這個(GNU 找到只):

find . -type f ! -newermt '2011-07-30 23:59' 
0

以下聲明似乎工作正常。 感謝大家的幫助。

find $1 -type f | \ 
sed 's/^/ls -l /g' | \ 
sh | \ 
awk -v filter_before=${FILTER_BEFORE} '{ if ($6 < filter_before) { print $8 } }'