2017-04-04 68 views
0

我想將一個JSON格式的文件放入一列,這樣做我認爲awk可以是一個很棒的工具。我的輸入是(例如):避免在awk中打​​印兩次最後一行

a 
b 
c 
d 
e 

而且我的輸出,我想的是:

{nodes:[{id='a'}, 
{id='b'}, 
{id='c'}, 
{id='d'}, 
{id='e'}]} 

我想有兩個不同的代碼。第一個是:

BEGIN{ 
FS = "\t" 
printf "{nodes:[" 
} 
{printf "{'id':'%s'},\n",$1} 
END{printf "{'id':'%s'}]}\n",$1} 

但是我打印兩次的最後一行:

{nodes:[{id='a'}, 
{id='b'}, 
{id='c'}, 
{id='d'}, 
{id='e'}, 
{id='e'}]} 

,我嘗試的另一種選擇是用函數getline:

BEGIN{ 
FS = "\t" 
printf "{nodes:[" 
} 
{printf getline==0 ? "{'id':'%s'}]}" : "{'id':'%s'},\n",$1} 

但出於某種原因,函數getline在最後一行總是1,而不是0,所以:

{nodes:[{id='a'}, 
{id='b'}, 
{id='c'}, 
{id='d'}, 
{id='e'}, 

有沒有解決我的問題的建議?

+1

這可能會幫助:http://stackoverflow.com/questions/11866860/how-do-you-skip -the-last-line-w-awk –

+2

你不使用valide json格式。除了數字和布爾值之外,每個名稱和值都需要用引號'''包圍,你應該使用工具'jq'來驗證你的json數據,它必須是'awk',還是可以創建一個簡單的'回聲'與它的所有東西? – suleiman

+0

都有理由,現在我的代碼工作 – oscarcapote

回答

1

在awk中。 outputing之前緩衝輸出變量b並對其進行處理:

$ awk 'BEGIN{b="{nodes:["}{b=b "{id=\x27" $0 "\x27},\n"}END{sub(/,\n$/,"]}",b);print b}' file 
{nodes:[{id='a'}, 
{id='b'}, 
{id='c'}, 
{id='d'}, 
{id='e'}]} 

解釋:

BEGIN { b="{nodes:[" }     # front matter 
     { b=b "{id=\x27" $0 "\x27},\n" } # middle 
END { sub(/,\n$/,"]}",b); print b } # end matter and replace ,\n in the end 
             # with something more appropriate 
+0

我不明白你爲什麼把\ x27 – oscarcapote

+1

嘗試用'''替換它們。「https://www.gnu.org/軟件/ GAWK /手動/ html_node/Quoting.html –

0

解決方案(感謝@Ruud和@suleiman)

BEGIN{ 
FS = "\t" 
printf "{'nodes':[" 
} 
NR > 1{printf "{'id':'%s'},\n",prev} 
{prev = $1} 
END{printf "{'id':'%s'}]}",prev} 
0

試試這個 -

$awk -v count=$(wc -l < f) 'BEGIN{kk=getline;printf "{nodes:[={'id':'%s'},\n",$kk} 
> { 
> if(NR < count) 
> { 
> {printf "{'id':'%s'},\n",$1} 
> }} 
> END{printf "{'id':'%s'}]}\n",$1}' f 
{nodes:[={id:a}, 
{id:b}, 
{id:c}, 
{id:d}, 
{id:e}]}