帮助shell脚本读取逗号分隔行中的模式,最终结果输出应再次以逗号分隔。在下面,例如,读取行以逗号分隔,并仅输出以逗号分隔的木偶字符串。
echo "docker-one,puppet-one,puppet-two,docker-three,puppet-four" | script
需要输出:
docker-one,docker-three
答案 0 :(得分:2)
awk
救援!
echo "docker-one,puppet-one,puppet-two,docker-three,puppet-four" |
awk 'BEGIN{RS=ORS=","} /puppet/'
puppet-one,puppet-two,puppet-four
表示docker,并替换最后一个逗号
echo "docker-one,puppet-one,puppet-two,docker-three,puppet-four" |
awk 'BEGIN{RS=ORS=","} /docker/' |
sed 's/,$/\n/'
docker-one,docker-three
或者,如果你的意思是 non puppet
echo "docker-one,puppet-one,puppet-two,docker-three,puppet-four" |
awk 'BEGIN{RS=ORS=","} !/puppet/' |
sed 's/,$/\n/'
docker-one,docker-three
答案 1 :(得分:2)
使用原生bash
regEx运算符~
并仅使用GNU paste
进行csv
格式设置,
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 :(得分: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
答案 3 :(得分: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