【问题标题】:Using awk to append columns on a file使用 awk 在文件中追加列
【发布时间】:2013-11-16 19:00:09
【问题描述】:

我有来自标准输出的数据列(在我的例子中是对 mysql 的调用),我想在每个循环中附加文件中的列。我该怎么办?

Standard output:

 a1
 a2
....
 an

保存在名为 table.dat 的文件中:

table.dat:

 a1
 a2
....
 an

然后产生另一个输出:

Further standard output:

 b1
 b2
....
 bn

附加到 table.dat:

table.dat:

 a1   b1
 a2   b2
.... ....
 an   bn

...等等。我可以使用粘贴,但我需要三个步骤:

 line producing standard output > tmpfile;
 paste prevfile tmpfile > table
 mv table prevfile;

有没有更快的方法,也许是使用 awk?

这个解决方案: Add a new column to the file 生成一个空表。

【问题讨论】:

  • 您可以使用paste tablefile <(program) 跳过一个临时文件。如果您有sponge,则可以添加| sponge tablefile 进行就地替换,否则您只需使用临时文件并重命名每次迭代即可。
  • [mysql call] | paste table - | sponge table 正是我所需要的,谢谢!令人难以置信的是moreutils debian 包中的这个“sponge”:我从来没有听说过!

标签: bash awk


【解决方案1】:

您可以通过从标准输入读取来使用这样的粘贴:

paste <(command1) <(command2)

例如

paste <(cat f1) <(cat f2)

代替:

paste f1 f2

【讨论】:

    【解决方案2】:

    只是为了澄清在给定两个流的情况下的一些细节,没有相同数量的元素。结果为paste as proposed by anubhava

    [ ~]$ cat t1.txt 
    a1
    a2
    a3
    [ ~]$ cat t2.txt 
    b1
    b2
    
    [ ~]$ paste t1.txt t2.txt 
    a1  b1
    a2  b2
    a3
    

    否则,使用 Bash 只是为了好玩:

    [ ~]$ cat test.sh 
    #!/bin/bash
    
    f1=t1.txt
    f2=t2.txt
    
    getNumberOfRows(){
        wc -l "$1"|cut -d" " -f1
    }
    
    s1=$(getNumberOfRows "$f1")
    s2=$(getNumberOfRows "$f2")
    [[ $s1 -le $s2 ]] && min="$s1" || min="$s2"
    
    i=1
    while read; do
        echo "$REPLY $(sed -n ${i}p $f2)"
       (( i++ ))
       [[ $i -ge $min ]] && break
    done < "$f1"
    
    [ ~]$ ./test.sh 
    a1 b1
    a2 b2
    [ ~]$
    

    在此示例中,您可以看到,如果文件大于另一个文件,我们不会显示额外的行。

    当然,您可以通过paste 中的命令输出或使用此脚本更改文件;)

    使用paste

    paste <(COMMAND1) <(COMMAND2)
    

    使用脚本:查看answer 以了解如何在循环中读取命令输出。

    【讨论】:

    • 对于纯 bash 解决方案:while read -u 4 a &amp;&amp; read -u 5 b; do echo "$a $b"; done 4&lt; file1 5&lt; file2 比您反复调用 sed 更有效。享受吧!
    • @gniourf_gniourf 谢谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-13
    • 2017-07-09
    • 2016-10-30
    • 1970-01-01
    • 2013-01-23
    • 2015-06-30
    • 1970-01-01
    相关资源
    最近更新 更多