1

While I was playing with awk's multi file processing construct

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

I asked myself, if it's possible to convert text files with different sizes for printing with awk like with

pr -mt file*

Assuming:

file1.txt

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

More arbitrary text of the first file.

file2.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.

The output sould be like this:

$ 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.  

How to achieve this with awk command only with having on file*.txt?

3
  • 2
    Why would you want to do this with awk though? There are far better tools like paste or pv which you mentioned. You would have to write a dedicated awk script for this, and that's kinda too broad a question. If you really want to do this, start writing it and ask if you get stuck.
    – terdon
    Aug 3, 2017 at 12:27
  • @terdon I know there are several easy and fancy ways to do this, even with vim. But while I was playing with awk's multi file processing construct, I want to achieve this task with awk. If this would be impossible, I would accept the answer.
    – John Goofy
    Aug 3, 2017 at 12:32
  • 1
    Not impossible, awk is a full programming language, you can write whatever you like in it. However, it will not be simple or practical and just, frankly, seems like a waste of time. Maybe someone will want to write it for you, but a far better approach would be to write it yourself and ask here if you have difficulty with a specific aspect of it.
    – terdon
    Aug 3, 2017 at 12:45

1 Answer 1

4

You could record all the lines of every file, noting the maximum line length and number of lines for each and then print all the lines in the end:

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
1
  • This is exactly what I was looking for and also very well explained. Thank you very much.
    – John Goofy
    Aug 3, 2017 at 13:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .