使用 cut 转置列的问题
problems transposing columns using cut
我想将一个 3 列的文本文件转置为三个单独的文件,每个文件一行。
也就是说,拿这个文件:
in_file
1 22 0.8
4 21 0.73
3 30 1.56
5 12 0.92
并生成以下 3 个文件:
out_file1
1 4 3 5
out_file2
22 21 30 12
out_file3
0.8 0.73 1.56 0.92
我试着用 cut 来做这个:
cut -d' ' -f1 in_file | tr -s '\n' '\t' >> out_file1
cut -d' ' -f2 in_file | tr -s '\n' '\t' >> out_file2
cut -d' ' -f3 in_file | tr -s '\n' '\t' >> out_file3
然而,我得到的是:
out_file1
1 4 3 5
out_file2
22 21 30 12
out_file3
0.8
0.73
1.56
0.92
我不明白为什么它适用于前两列而不适用于第三列。
感谢任何帮助!
如果有 awk 的话会快一点
awk '{ for( i=1; i<=NF; i++) printf( "%s ", $i) > ("file" i)}' YourFile
注意:
- >
而不是 >>
因为 awk 仅在文件打开时评估重定向(因此在这种情况下创建而不是添加)
对于你的剪切问题,分隔符总是 1 space 列之间的字符
您的问题很可能是您输入的分隔符作为文字制表符而不是 \t
,这是一个执行所有三个文件的循环:
for i in {1..3}; do
cut -d$'\t' "-f${i}" in_file | column >> "outfile_${i}.txt"
done
这里我们遍历 {1..3}
的序列,使用特殊语法将分隔符设置为制表符:-d$'\t'
,将数据通过管道传输到 column
,它会自动排列值和将其附加到正确的文件中。
我想将一个 3 列的文本文件转置为三个单独的文件,每个文件一行。 也就是说,拿这个文件:
in_file
1 22 0.8
4 21 0.73
3 30 1.56
5 12 0.92
并生成以下 3 个文件:
out_file1
1 4 3 5
out_file2
22 21 30 12
out_file3
0.8 0.73 1.56 0.92
我试着用 cut 来做这个:
cut -d' ' -f1 in_file | tr -s '\n' '\t' >> out_file1
cut -d' ' -f2 in_file | tr -s '\n' '\t' >> out_file2
cut -d' ' -f3 in_file | tr -s '\n' '\t' >> out_file3
然而,我得到的是:
out_file1
1 4 3 5
out_file2
22 21 30 12
out_file3
0.8
0.73
1.56
0.92
我不明白为什么它适用于前两列而不适用于第三列。
感谢任何帮助!
如果有 awk 的话会快一点
awk '{ for( i=1; i<=NF; i++) printf( "%s ", $i) > ("file" i)}' YourFile
注意:
- >
而不是 >>
因为 awk 仅在文件打开时评估重定向(因此在这种情况下创建而不是添加)
对于你的剪切问题,分隔符总是 1 space 列之间的字符
您的问题很可能是您输入的分隔符作为文字制表符而不是 \t
,这是一个执行所有三个文件的循环:
for i in {1..3}; do
cut -d$'\t' "-f${i}" in_file | column >> "outfile_${i}.txt"
done
这里我们遍历 {1..3}
的序列,使用特殊语法将分隔符设置为制表符:-d$'\t'
,将数据通过管道传输到 column
,它会自动排列值和将其附加到正确的文件中。