我正在尝试编写一个脚本,它读取下面的文件内容,并提取每行第6列的值,然后打印每行,而不打印第6列。逗号用作分隔符。
输入:
123,456,789,101,145,5671,hello world,goodbye for now
223,456,789,101,145,5672,hello world,goodbye for now
323,456,789,101,145,5673,hello world,goodbye for now我所做的是
#!/bin/bash
for i in `cat test_input.txt`
do
COLUMN=`echo $i | cut -f6 -d','`
echo $i | cut -f1-5,7- -d',' >> test_$COLUMN.txt
done我得到的输出是
test_5671.txt:
123,456,789,101,145,hellotest_5672.txt:
223,456,789,101,145,hellotest_5673.txt:
323,456,789,101,145,hello"world,再见“的其余部分没有写入到输出文件中,因为"hello”和"world“之间的空格似乎被用作分隔符?
如何获得正确的输出
123,456,789,101,145,hello world,goodbye for now发布于 2012-04-18 18:35:57
这不是cut命令的问题,而是您正在使用的for循环的问题。对于第一次循环运行,变量i将只包含123,456,789,101,145,5671,hello。
如果您坚持逐行读取输入文件(效率不是很高),那么最好使用这样的read-loop:
while read i
do
...
done < test_input.txt发布于 2012-04-18 18:50:33
echo '123,456,789,101,145,5671,hello world,goodbye for now' | while IFS=, read -r one two three four five six seven eight rest
do
echo "$six"
echo "$one,$two,$three,$four,$five,$seven,$eight${rest:+,$rest}"
done打印:
5671
123,456,789,101,145,hello world,goodbye for now有关man bash语法,请参阅:+ Parameter Expansion一节(实际上,如果定义了$rest且非空,它将输出一个逗号和$rest )。
还有,you shouldn't use for to loop over file contents。
发布于 2012-04-18 19:09:12
作为ktf mentioned,您的问题不在于cut,而在于您将代码行传递给cut的方式。他/她提供的解决方案应该是有效的。
或者,您可以使用一行awk来实现相同的行为
awk -F, '{for(i=1;i<=NF;i++) {if(i!=6) printf "%s%s",$i,(i==NF)?"\n":"," > "test_"$6".txt"}}' test_input.txt为了清楚起见,这里有一个详细的版本:
awk -F, ' # "-F,": using comma as field separator
{ # for each line in file
for(i=1;i<=NF;i++) { # for each column
sep = (i == NF) ? "\n" : "," # column separator
outfile = "test_"$6".txt" # output file
if (i != 6) { # skip sixth column
printf "%s%s", $i, sep > outfile
}
}
}' test_input.txthttps://stackoverflow.com/questions/10207512
复制相似问题