如何在shell脚本中连接两个文件

时间:2013-12-11 15:27:14

标签: shell unix paste

我在unix中有两个文件。我只想添加两列文件内容

file 1:                  file 2:

2013-09-09 5656          2013-09-09 4321
2013-09-10 1234          2013-09-10 3234
                         2013-09-11 5056
                         2013-09-12 1256

我使用了以下内容:

paste -d " " file1 file2>file3 

但它没有按预期工作

我需要输出如:

2013-09-09 5656     2013-09-09 4321
2013-09-10 1234     2013-09-10 3234
                    2013-09-11 5056
                    2013-09-12 1256

paste -d“”file1 file2返回:

2013-09-09 5656     2013-09-09 4321
2013-09-10 1234     2013-09-10 3234
2013-09-11 5056
2013-09-12 1256

2 个答案:

答案 0 :(得分:3)

pr是工作的工具:

$ pr -m -t file1 file2

答案 1 :(得分:0)

paste不会尝试在列中整齐地对齐文件。它只是在列之间插入分隔符。如果默认paste file1 file2对您不起作用,那么您需要自己解决问题。

例如:

# Assign file1 and file2 to file descriptors 3 and 4 so we can read from them
# simultaneously in the loop.
exec 3< file1 || exit
exec 4< file2 || exit

while true; do
    # Keep looping as long as we've read a line from either file.
    # Don't stop until both files are exhausted.
    line_read=0
    read a <&3 && line_read=1
    read b <&4 && line_read=1
    ((line_read)) || break

    # Use `%-20s' to ensure each column is 20 characters wide at minimum.
    printf '%-20s %-20s\n' "$a" "$b"
done