1

我正在尝试编写一个脚本来读取下面的文件内容并提取每行第 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,hello

test_5672.txt:

223,456,789,101,145,hello

test_5673.txt:

323,456,789,101,145,hello

“世界,现在再见”的其余部分没有写入输出文件,因为看起来“你好”和“世界”之间的空格被用作分隔符?

如何获得正确的输出

123,456,789,101,145,hello world,goodbye for now
4

4 回答 4

2

It's not a problem with the cut command but with the for loop you're using. For the first loop run the variable i will only contain 123,456,789,101,145,5671,hello.

If you insist to read the input file line-by-line (not very efficient), you'd better use a read-loop like this:

while read i
 do
  ...
 done < test_input.txt
于 2012-04-18T10:35:56.690 回答
1
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部分:+(基本上它输出一个逗号,并且$restif$rest已定义非空)。

此外,您不应该使用for循环文件内容

于 2012-04-18T10:50:32.980 回答
1

正如ktf 提到的,您的问题不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.txt
于 2012-04-18T11:09:12.347 回答
0

an easy method id to use tr commende to convert the espace carracter into # and after doing the cat commande retranslate it into the espace.

于 2012-04-18T10:32:01.903 回答