2017-04-19 90 views
-2

幫助shell腳本以逗號分隔的行讀取模式,最終結果輸出應再次以逗號分隔。在下面的例如read行中用逗號分隔,並只輸出用逗號隔開的木偶字符串。awk腳本讀取行匹配模式和結果用逗號分隔輸出

echo "docker-one,puppet-one,puppet-two,docker-three,puppet-four" | script 

輸出要求:

docker-one,docker-three 
+2

你試過的代碼在哪裏?這是相當基本的東西...... –

+0

IFS =「,」for v in $ variable;做echo $ v | grep -v puppet;完成 – iaav

+0

Buti需要輸出爲逗號分隔 – iaav

回答

2

awk來救援!

echo "docker-one,puppet-one,puppet-two,docker-three,puppet-four" | 
awk 'BEGIN{RS=ORS=","} /puppet/' 

puppet-one,puppet-two,puppet-four 

的碼頭工人,並替換最後一個逗號

echo "docker-one,puppet-one,puppet-two,docker-three,puppet-four" | 
awk 'BEGIN{RS=ORS=","} /docker/' | 
sed 's/,$/\n/' 

docker-one,docker-three 

,或者,如果你的意思是非傀儡

echo "docker-one,puppet-one,puppet-two,docker-three,puppet-four" | 
awk 'BEGIN{RS=ORS=","} !/puppet/' | 
sed 's/,$/\n/' 

docker-one,docker-three 
+0

對不起,預期輸出「docker-one,docker-three」 – iaav

+0

如果最後一個字符串不包含puppet,那麼將在輸出結尾處產生一個沒有後續換行符的逗號。 –

+0

已更新問題。謝謝 – iaav

2

使用本機bash正則表達式運算符~csv格式使用GNU paste獨自一人,

IFS="," read -ra myArray <<<"docker-one,puppet-one,puppet-two,docker-three,puppet-four" 
for i in "${myArray[@]}";do [[ $i =~ ^puppet ]] && echo "$i" ; done | paste -sd ',' 

產生一個輸出作爲

puppet-one,puppet-two,puppet-four 

和其他琴絃比開始puppet的那些,做了否定的正則表達式匹配,

for i in "${myArray[@]}";do [[ ! $i =~ ^puppet ]] && echo "$i" ; done | paste -sd ',' 
docker-one,docker-three 
2

這聽起來像其中之一可能是什麼您正在查找:

$ echo "docker-one,puppet-one,puppet-two,docker-three,puppet-four" | 
awk -F, '{for (i=1;i<=NF;i++) if ($i ~ /puppet/) printf "%s%s", (c++?FS:""), $i; print ""}' 
puppet-one,puppet-two,puppet-four 

$ echo "docker-one,puppet-one,puppet-two,docker-three,puppet-four" | 
awk -F, '{for (i=1;i<=NF;i++) if ($i !~ /puppet/) printf "%s%s", (c++?FS:""), $i; print ""}' 
docker-one,docker-three 

$ echo "docker-one,puppet-one,puppet-two,docker-three,puppet-four" | 
awk -F, '{for (i=1;i<=NF;i++) if ($i ~ /docker/) printf "%s%s", (c++?FS:""), $i; print ""}' 
docker-one,docker-three 
0

使用tr, grep和paste:

$ echo "docker-one,puppet-one,puppet-two,docker-three,puppet-four" \ 
     | tr , '\n' | grep -v puppet | paste -s -d , - 
docker-one,docker-three