的Unix Shell脚本:AWK/SED循环
我有一个文件的条目类似如下:的Unix Shell脚本:AWK/SED循环
root:x:0::192.168.164.164
bin:x:1:bin,daemon:192.168.164.164
daemon:x:2:bin,daemon:192.168.164.164
test:x:501:test1,test2,test3,test4:192.168.164.160
test5:x:502::192.168.164.160
我一直在寻找UNIX的bash/shell脚本的方式通过该文件可以转化为:
root;0;;192.168.164.164
bin;1;bin;192.168.164.164
bin;1;daemon;192.168.164.164
daemon;2;bin;192.168.164.164
daemon;2;daemon;192.168.164.164
test;501;test1;192.168.164.160
test;501;test2;192.168.164.160
test;501;test3;192.168.164.160
test;501;test4;192.168.164.160
test5;502;;192.168.164.160
在bash:
while IFS=: read -r a b c d e; do
while IFS=, read -r -a i; do
[[ ${#i[@]} -eq 0 ]] && i=""
for j in "${i[@]}"; do
echo "$a;$c;$j;$e"
done
done <<< "$d"
done < file
输出:
root;0;;192.168.164.164 bin;1;bin;192.168.164.164 bin;1;daemon;192.168.164.164 daemon;2;bin;192.168.164.164 daemon;2;daemon;192.168.164.164 test;501;test1;192.168.164.160 test;501;test2;192.168.164.160 test;501;test3;192.168.164.160 test;501;test4;192.168.164.160 test5;502;;192.168.164.160
鉴于你新更新的要求:
awk -F'[:,]' -v OFS=';' '{for(i=4;i<NF;i++) print $1, $3, $i, $NF}' file
这很好,谢谢!但我正在玩另一个实际测试案例,其中文件包含另一个条目,如: testuser4:x:502 :: 192.168.164.160 然后代码去掉(如预期的)502到192.168.164.160之间的所有内容。但是,它应该显示类似于 testuser4; 502 ;; 192.168.164.160 –
道歉 - 我对测试用例和问题文本感到无情。我现在纠正了他们。 –
感谢您的反馈和答案,Ed!在下次发布之前,请牢记您的建议。这就像一个魅力:) –
的Perl:
perl -F'[:,]' -lanE '$,=";"; print @F[0,2],$_,$F[-1] for @F[3..$#F-1]' file
似乎是一个微不足道的'awk'命令。使用':'作为输入字段分隔符,';'作为输出字段分隔符,然后打印您想要的字段。 – Barmar
啊,这比它稍微复杂一些。当字段4包含逗号时,您需要将其拆分,然后为该数组的每个元素重复打印。 – Barmar
所以这行'test:x:501:test1,test2,test3,test4:192.168.164.160'应该转换成'test; 501; test1; 192.168.164.160 test; 501; test2; 192.168.164.160 test; 501; test3; 192.168.164.160 test; 501; test4; 192.168.164.160',对吧? – RomanPerekhrest