Linux 将文件分成两列

Linux split a file in two columns

我有以下包含 2 列的文件:

A:B:IP:80                  apples    
C:D:IP2:82                 oranges    
E:F:IP3:84                 grapes

如何将文件拆分为 2 个其他文件,文件中的每一列如下所示:

文件 1

A:B:IP:80    
C:D:IP2:82    
E:F:IP3:84

文件 2

apples
oranges
grapes

Perl 1-liner 使用(滥用)print 转到 STDOUT 的事实,即文件描述符 1warn 转到 STDERR,即文件描述符 2:

 # perl -n means loop over the lines of input automatically
 # perl -e means execute the following code
 # chomp means remove the trailing newline from the expression

 perl -ne 'chomp(my @cols = split /\s+/); # Split each line on whitespace
           print $cols[0] . "\n";
           warn  $cols[1] . "\n"' <input 1>col1 2>col2

当然,您可以只对适当的列使用 cut -b,但是您需要读取文件两次。

尝试:

awk '{print >"file1"; print >"file2"}' file

运行该命令后,我们可以验证是否已创建所需的文件:

$ cat file1
A:B:IP:80
C:D:IP2:82
E:F:IP3:84

并且:

$ cat file2
apples
oranges
grapes

工作原理

  • print >"file1"

    这告诉 awk 将第一列写入 file1

  • print >"file2"

    这告诉 awk 将第二列写入 file2

这是一个适用于任意数量列的 awk 解决方案:

awk '{for(n=1;n<=NF;n++)print $n>"File"n}' input.txt

这一步步遍历行中的每个字段,并根据列号将字段打印到不同的输出文件。

请注意,空白字段——或者更确切地说,字段少于其他行的行将导致行号不匹配。也就是说,如果您的输入是:

A 1
B
C 3

那么 File2 将包含:

1
3

如果这是一个问题,请在您的问题更新中提及。


您当然可以通过多种方式仅在 bash 中完成此操作。这是一个:

while read -r line; do
  a=($line)
  for m in "${!a[@]}"; do
    printf '%s\n' "${a[$m]}" >> File$((m+1))
  done
done < input.txt

这会将每行输入读入 $line,然后将 word-splits $line 读入 $a[] 数组中的值。然后遍历该数组,将每个项目打印到适当的文件,以数组的索引命名(加一,因为 bash 数组从零开始)。