合并多个文件并将输出格式化为带换行的列

合并多个文件并将输出格式化为带换行的列

我试图在更少的时间内向用户显示多个文件。这些文件的行相对较长,并且包含相同的文本,但语言不同(行长度存在差异是可以预料的)。

例子:

文件1.txt

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut lectus arcu bibendum at.

file2.txt(以上,但谷歌翻译)

The pain itself is the love of the pain, the main ecological problems, but I give this kind of time to fall down, so that some great pain and pain.
To drink at the bed of the bow.

预期结果:

Lorem ipsum dolor sit amet, consectetur adipiscing    The pain itself is the love of the pain, the main
elit, sed do eiusmod tempor incididunt ut labore et   ecological problems, but I give this kind of time
dolore magna aliqua.                                  to fall down, so that some great pain and pain.
Ut lectus arcu bibendum at.                           To drink at the bed of the bow.

如果某一行比其相应行短且不换行,则剩余空间应保留为空。这应该适用于 2 个和 3 个文件,并更改分隔线以适应屏幕尺寸。我尝试将paste 与column 和pr 一起使用以使其工作。优先考虑 POSIX 合规性。

paste file1.txt file2.txt | column -t -s $'\t'

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua.                       The pain itself is the love of the pain, the main ecological
problems, but I give this kind of time to fall down, so that some great pain and pain.
Ut lectus arcu bibendum at.                To drink at the bed of the bow.

问题是,第一个文件中的行在到达终端中心时不会换行,而第二个文件会换行,但它从行的开头而不是中心开始。

任何帮助表示赞赏

答案1

进行换行第一的fold

paste <(fold -sw 40 file1.txt) <(fold -sw 40 file2.txt) | column -t -s $'\t'

如果您希望它适应您的终端大小,请执行以下操作

width=$(( (COLUMNS - 4) / 2))
paste <(fold -sw $width file1.txt) <(fold -sw $width file2.txt) | column -t -s $'\t'

要并排换行,我们必须逐行遍历文件:

while IFS= read -r -u3 line1
      IFS= read -r -u4 line2
do
    paste <(fold -sw $width <<<"$line1") \
          <(fold -sw $width <<<"$line2")

done 3< file1.txt 4< file2.txt \
| column -t -s $'\t'

给定您的示例输入文件和宽度 45,这会产生

Lorem ipsum dolor sit amet, consectetur       The pain itself is the love of the pain, the
adipiscing elit, sed do eiusmod tempor        main ecological problems, but I give this
incididunt ut labore et dolore magna aliqua.  kind of time to fall down, so that some
great pain and pain.
Ut lectus arcu bibendum at.                   To drink at the bed of the bow.

至此,我们已经超越了 POSIX shell:那就是 bash。我们也应该考虑使用不同的编程语言。

相关内容