2016-09-21 210 views
0

需要從JSON文件中提取每行兩個變量,並在單獨的後續命令中使用這兩個變量中的每一個。在shell腳本中將bash變量傳遞給python命令

我的劇本是迄今爲止:

#!/bin/bash 

VCTRL_OUT='/tmp/workingfile.json' 

old_IFS=$IFS  # save the field separator 
IFS=$'\n'  # new field separator, the end of line 

for line in $(cat $VCTRL_OUT) 
    do 
    python -c 'import json,sys;obj=json.load($line);print obj["ip_range"]' 
    done 

的倒數第二行是錯誤的,需要知道如何做到這一點。

以下工作:

cat /tmp/workingfile.json | head -n +1 | python -c 'import json,sys;obj=json.load(sys.stdin);print obj["ip_range"]'; 

,但不知道如何爲循環做同樣的bash腳本。

+0

bash中的單引號殺死所有特殊字符,甚至是$ line變量中的'$',所以不是變量的值,而是傳遞'「$ line」'字符串。你需要在'python -c ...'命令周圍使用雙引號。 – karlosss

+0

JSON文件是什麼樣的?比試圖爲文件的每一行運行單獨的Python程序有更好的選擇。 (忽略JSON不是面向行並且通常不能被逐行處理的這一事實,這是在'bash'中迭代文件的錯誤方法;請參見[Bash FAQ 001](http:// myjie.wooledge.org/BashFAQ/001)。) – chepner

+0

@karlosss - 現在運行的json.load命令現在不起作用,因爲它是針對json行運行的。什麼需要修改? – dross

回答

3

Python的不會是我對於這種只有一行的第一選擇,但你可以嘗試

#!/bin/bash 

VCTRL_OUT='/tmp/workingfile.json' 

parse_json() { 
    python -c $'import json,fileinput,operator\nfor line in fileinput.input(): print "%s %s"%operator.itemgetter("ip_range","description")(json.loads(line))' "$1" 
} 
while IFS= read -r ip_range description; do 
    # do your thing with ip_range 
done < <(parse_json "$VCTRL_OUT") 

一種選擇是用jq更換的Python位:

while IFS= read -r ip_range description; do 
    # ... 
done < <(jq -rRc 'fromjson | .ip_range+" "+.description' "$VCTRL_OUT") 

另一個另一種方法是用Python替換整個bash腳本,但根據bash腳本的實際情況,說起來容易做起來難。

相關問題