使用bash读取两个文件的嵌套循环 [英] Nested loop for reading two files with bash

查看:238
本文介绍了使用bash读取两个文件的嵌套循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试使用以下代码合并两个输入文件:

I'm currently trying to use the following code to merge two input files:

for i in `cat $file1`; do
    for j in `cat $file2`; do
        printf "%s %s\n" "$i" "$j"
    done
done

给出如下创建的文件:

printf '%s\n' A B C >file1
printf '%s\n' 1 2 3 >file2

...我的预期/期望输出是:

...my expected/desired output is:

A 1
B 2
C 3

但是,我得到的输出是:

But instead, the output I'm getting is:

A 1
A 2
A 3
B 1
B 2
B 3
C 1
C 2
C 3

如何解决?

推荐答案

可以使用coreutils中的pr命令,也可以与其他命令/工具(例如粘贴)以及Shell和AWK脚本一起使用. 通过使用来自coreutils的命令来节省精力,因为在命令行上只需要几个参数,就像下面的示例一样:

Possible by using the pr command from coreutils, also possible with other commands/tools like paste and also by Shell and AWK scripts. Least effort by using the commands from coreutils as only a few parameters are required on the commandline, like in this example:

pr -TmJS" " file1 file2

其中:

  • -T关闭分页
  • -mJ合并文件,加入整行
  • -S" "用空格分隔列
  • -T turns off pagination
  • -mJ merge files, Joining full lines
  • -S" " separate the columns with a blank

这篇关于使用bash读取两个文件的嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆