控制awk输出中的间距

时间:2012-06-16 04:49:38

标签: bash sed awk grep gnuplot

我有两个文本文件。 hash_only.txt和final_output.txt hash_only.txt如下所示。

193548
401125
401275

final_output.txt如下所示。

193548      1199687744  5698758206701808640
193548      1216464960  5698758206761818112
193548      1216464960  5698758206778417152
193548      4236691520  5698758206778945280
401125      2138607488  5698762375908890880
401125       863932288  5698762375909423360
401125      3884158848  5698762375910044160
401125      2609483648  5698762375911032320

我写了一个脚本,如下所示。

awk '
FNR==NR {
    hash[$1]
    next
}
$1 in hash {
    print $2,'\t',$3 >> "ecast_print_"$1;
}' hash_only.txt final_output.txt

对于hash_only.txt中的所有值,例如193548,401125等,我想从文件'final_output.txt'中提取第2,3列,其中第1列与193548,401125等匹配并输出 第2,3栏至print_193548,print_401125等 这将产生如下所示的输出。

1133254688 5698771509078629376
1150031904 5698771509371165696
1150031904 5698771510035551232
4170258464 5698771510036082688
2895583264 5698771510036715520
1620908064 5698771510037202176
346232864 5698771510037665280
3366459424 5698771510038193664
2091784224 5698771510332259072
817109024 5698771510332816128
3837335584 5698771510333344512
2562660384 5698771510339882240

正如您在上面看到的那样,输出未对齐,其中第一个字段的长度小于正常。我希望第二行从确切的位置开始。我需要这个以便将其作为gnuplot的输入。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

您可以考虑使用printf来获得具有一致宽度的字段。

另外,gnuplot不介意文件中的字段是否完全对齐,如果这是你想要的。所有必要的是字段用空格分隔。

答案 1 :(得分:1)

这可能适合你(GNU sed):

sed 's|.*|/^& /{s/.\\{12\\}//;w ecast_print_&\n}|' hash_only.txt |
sed -nf - final_output.txt

说明:

hash_only.txt文件创建一个sed脚本,该脚本将匹配的行写入文件名ecast_print_,并附加密钥。从提供给sed脚本的输入文件中删除前12个字符。