Linux-循环遍历每一行的每个元素
我有一个包含以下信息的文本文件:
cat test.txt
a,e,c,d,e,f,g,h
d,A,e,f,g,h
我希望遍历每一行,然后为每一行打印与 e 不同的所有字符的索引。所以理想的输出要么是制表符分隔符,要么是逗号分隔符
1 3 4 6 7 8
1 2 4 5 6
or
1,3,4,6,7,8
1,2,4,5,6
我设法遍历每一行并打印索引,但结果被打印到同一行而不是分开的。
while read line;do echo "$line" | awk -F, -v ORS=' ' '{for(i=1;i<=NF;i++) if($i!="e") {print i}}' ;done<test.txt
结果是
1 3 4 6 7 8 1 2 4 5 6
如果我只使用 awk
awk -F, -v ORS=' ' '{for(i=1;i<=NF;i++) if($i!="e") {print i}}'
我得到相同的输出
任何人都可以通过分隔线来帮助我解决这个特定问题。
回答
如果你不介意一些尾随空格,你可以这样做:
while read line;do echo "$line" | awk -F, '{for(i=1;i<=NF;i++) if($i!="e") {printf i " "}; print ""}' ;done<test.txt
但省略while循环并执行以下操作会更典型:
awk -F, '{for(i=1;i<=NF;i++) if($i!="e") {printf i " "}; print ""}' <test.txt
您可以通过稍微神秘的方式避免尾随空格:
awk -F, '{m=0; for(i=1;i<=NF;i++) if($i!="e") {printf "%c%d", m++ ? " " : "", i }; print ""}' <test.txt
- @accdias correct. The pro to using input redirection is that if you're also redirecting output to a file, e.g. `awk 'script' <input >output` then if the input can't be opened the output won't be created/emptied. The con is that you do not have the name of the input file in the FILENAME variable. IMHO the pro isn't generally worth the con for 1 input file and you can't use it in the common case where you have multiple input files so it's not worth using unless you have a very specific need to do so such as you absolutely must not zap the output file if the single input file can't be opened.