【问题标题】:How to copy second column from all the files in the directory and place them as columns in a new text file如何从目录中的所有文件中复制第二列并将它们作为列放在新的文本文件中
【发布时间】:2015-12-08 18:03:50
【问题描述】:

我有 150 个制表符分隔的文本文件,我想复制每个文件的第 2 列并粘贴到另一个新文本文件中。新文件将有 150 列,每个文件的第二列。帮帮我,伙计们。 此代码有效,但将每一列放在另一列之下,形成一个 loooong 列。

for file in *.txt
do
   awk '{print $2}' *.txt > AllCol.txt
done

【问题讨论】:

标签: file awk multiple-columns


【解决方案1】:

这是另一种不循环的方法

$ c=$(ls -1 file*.tsv | wc -l); cut -f2 file*.tsv | pr  -$c -t

【讨论】:

    【解决方案2】:
    #!/bin/bash
    
    # Be sure the file suffix of the new file is not .txt
    OUT=AllColumns.tsv
    touch $OUT
    
    for file in *.txt
    do
      paste $OUT <(awk -F\\t '{print $2}' $file) > $OUT.tmp
      mv $OUT.tmp $OUT
    done
    

    许多替代方法之一是使用cut -f 2 而不是awk,但您使用awk 标记了您的问题。

    由于您的文件非常规则,您也可以跳过 do 循环,并使用命令行实用程序,例如 rs(重塑)或 datamash

    【讨论】:

    • 非常感谢兄弟。
    • @Mikko - 不客气。您能否因此“接受”答案?
    猜你喜欢
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多