2014-02-09 22 views
0

我有很多行的這種格式的文本文件(定義爲一組每兩#之間的線路)線路組:保持與特定的關鍵字(bash)的

# some str for test 
hdfv 12 9 b 
cgj 5 11 t 
# another string to examine 
kinj 58 96 f 
dfg 7 26 u 
fds 9 76 j 
--- 
key.txt: 
string to 
--- 
output: 
# another string to examine 
kinj 58 96 f 
dfg 7 26 u 
fds 9 76 j 

我應該尋找一些關鍵詞(string,to)以#開頭的行,如果關鍵字不存在於key.txt(一個有兩列的文件)中,那麼我應該刪除該行和該行的下一行(這個組)。我寫了這個代碼無結果!(關鍵詞以輸入文件爲例)

cat input.txt | while IFS=$'#' read -r -a myarray 
do 
a=${myarray[1]} 
b=${myarray[0]} 
unset IFS 
read -r a x y z <<< "$a" 
key=$(echo "$x $y") 
if grep "$key" key.txt > /dev/null 
then 
echo $key exists 
else 
grep -v -e "$a" -e "$b" input.txt > $$ && mv $$ input.txt 
fi 
done 

有人可以幫我嗎?

回答

0

一種簡單的方式來獲得正確的塊使用awk和正確的記錄選擇:

awk 'FNR==NR {a[$0];next} { RS="#";for (i in a) if ($0~i) print}' key.txt input.txt 
another string to examine 
kinj 58 96 f 
dfg 7 26 u 
fds 9 76 j 

這應該重新插入使用#和刪除多餘的空行。我可能是更簡單的方法來做到這一點,但這是有效的。

awk 'FNR==NR {a[$0];next} { RS="#";for (i in a) if ($0~i) {sub(/^ /,RS);sub(/\n$/,x);print}}' key.txt input.txt 
#another string to examine 
kinj 58 96 f 
dfg 7 26 u 
fds 9 76 j 
+0

更新給我們的數據從'key.txt' – Jotne

+0

增加了第二個答案來修復丟失''#和刪除多餘的空行。刪除的空白在哪裏? – Jotne