2014-04-20 30 views
0

我寫了這個測試腳本:AWK拋出錯誤「WK:CMD線:1:BEGIN塊必須有一個行爲部分」

#!/bin/bash 

build_message='build' 

# On first run, the supplied settings block is appended to the supplied config 
# file surrounded by comments ("# build START" and "# build END"). 
# On subsequent runs, the lines in between the two comments will be replaced 
# by the provided settings block. 
config-insert() { 
    settings="$1" 
    file="$2" 
    awk='BEGIN { p = 1; o = 1; } 
     $0 ~ "^# " m " START" { p = 0; if (o) output(); o = 0; } 
     $0 ~ "^# " m " END"{ p = 1; next } 
     END { if (o) output(o); } 
     { if (p) print $0; } 
     function output() { print "# " m " START\n" s "\n# " m " END"; }' 
    awk -v m="$build_message" -v s="$settings" $awk $file > $file 
} 

config-insert "setting block" testfile 

當我運行它,我得到一個奇怪的錯誤:

在引號

awk: cmd. line:1: BEGIN blocks must have an action part

+1

你想要寫'awk'的任何特殊原因? 'awk'不是'bash',並且不符合你在bash中期望的擴展。另外請注意,您正在將文件的輸出重定向到同一個文件。 –

+0

喜歡什麼?你會如何寫它? – mattalxndr

+0

我無法編寫看代碼的代碼。如果你可以把一些樣本輸入數據和你的預期輸出,那麼可能是我可以。 –

回答

2

認沽$ AWK:

awk -v m="$build_message" -v s="$settings" "$awk" "$file" 
+5

請不要在_single quotes_中。 – devnull

+1

雙引號使用'$ awk'的整個值構成一個參數。單引號構成一個字符串,其字面值爲'$ awk'。沒有引號爲'$ awk'的值中的每個單詞生成一系列參數。 – poolie

1

外殼是吃你的報價。通常,當我用awk/bash/sed腳本解決這類問題時,我使用臨時文件。

... 
    tempfile=$(mktemp) 
    echo ${awk} >${tempfile}  
    awk ... -f ${tempfile} ... 
    rm ${tempfile} 

根據您希望的安全等級,您可以使用mktemp來創建目錄而不是文件。

相關問題