bash 使用 awk 在文件中附加列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19796863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:30:21  来源:igfitidea点击:

Using awk to append columns on a file

bashawk

提问by leonard vertighel

I have columns of data arriving from standard output (in my case a call to mysql), and I would like to append at each loop the column in a file. How can I do?

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

Standard output:

 a1
 a2
....
 an

Saving in a file called table.dat:

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

table.dat:

 a1
 a2
....
 an

Then another output is produced:

然后产生另一个输出:

Further standard output:

 b1
 b2
....
 bn

Appending to table.dat:

附加到 table.dat:

table.dat:

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

...and so on. I can use paste, but I need three steps:

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

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

Is there a faster way, maybe by using awk?

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

This solution: Add a new column to the fileproduces an empty table.

此解决方案: 向文件中添加一个新列会生成一个空表。

回答by anubhava

You can use paste like this by reading from stdin:

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

paste <(command1) <(command2)

e.g.

例如

paste <(cat f1) <(cat f2)

instead of:

代替:

paste f1 f2

回答by Idriss Neumann

Just to clarify some details in the case where the two streams given, don't have the same number of elements. Result with pasteas proposed by anubhava:

只是为了澄清给出的两个流的情况下的一些细节,不要具有相同数量的元素。结果与pasteanubhava 提出的一样

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

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

Otherwise, with Bash just for fun :

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

[ ~]$ cat test.sh 
#!/bin/bash

f1=t1.txt
f2=t2.txt

getNumberOfRows(){
    wc -l ""|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
[ ~]$

In this example you could see that we don't display additional lines if a file is larger than the other.

在这个例子中,你可以看到如果一个文件比另一个大,我们不会显示额外的行。

Of course you could change files by command outputs in either pasteor with this script ;)

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

Using paste:

使用paste

paste <(COMMAND1) <(COMMAND2)

Using the script : see this answerto see how to read a command output in a loop.

使用脚本:请参阅此答案以了解如何在循环中读取命令输出。