awk:模拟“pr -mt 文件*”

awk:模拟“pr -mt 文件*”

当我在玩 的awk多文件处理结构时

awk 'NR == FNR { # some actions; next} # other condition {# other actions}' file*.txt

我问自己,是否可以转换不同大小的文本文件以进行awk打印

pr -mt file*

假设:

文件1.txt

arbitrary text of the first file,
which is not so long.

More arbitrary text of the first file.

文件2.txt:

Arbitrary text of the second file.
More arbitrary text of the second file.
More and More arbitrary text of the second file.
It's going on.
But finally every text will end.

输出应该是这样的:

$ pr -w150 -mt file*
arbitrary text of the first file,         Arbitrary text of the second file.            
which is not so long.                     More arbitrary text of the second file.       
                                          More and More arbitrary text of the second file.  
More arbitrary text of the first file.    It's going on.                    
                                          But finally every text will end.  

如何awk仅通过命令来实现这一点file*.txt

答案1

您可以记录每个文件的所有行,记下每个文件的最大行长度和行数,然后最后打印所有行:

awk '
  FNR == 1 {f++}
  {line[f, FNR] = $0}
  length > width[f] {width[f] = length}
  FNR > max_lines {max_lines = FNR}
  END{
    for (row = 1; row <= max_lines; row++) {
      for (i = 1; i <= f; i++)
        printf "%-*s", (i == f ? 0 : width[i] + 2), line[i, row]
      print ""
    }
  }' ./*.txt

相关内容