awk line break after each file

2020-05-06 13:44发布

问题:

With this script every field is printed out according to the longest word of the current file, but needs to have a line break every file. How can this be achieved?

awk 'BEGIN{ORS="\n"}FNR=NR{a[i++]=$0; if(length($0) > length(max)) max=$0;l=length(max)}  END{ for(j=1; j<=i;j++) printf("%-"(l+1)"s,",a[j-1])}' file1 file2 >outfile

file1

HELLO
WORLD
SOUTH IS
WARM
NORTH IS
COLD

file2

HELLO
WORLD
SOUTH
WARM
NORTH
COLD

output

HELLO     ,WORLD     ,SOUTH IS  ,WARM      ,NORTH IS  ,COLD      
HELLO ,WORLD ,SOUTH ,WARM  ,NORTH ,COLD  

回答1:

It's not entirely clear what you are asking for, but perhaps you just want:

FNR==1 {print "\n"}

Which will print a newline whenever it starts reading the first line of a file. Make sure this pattern/action is before any others so that the newline prints before any other action prints anything for the first line of the current file. (This does not appear to apply in your case, since no such action exists.)



回答2:

Took me some time, got it solved with this script.

awk '{ NR>1 && FNR==1 ? l=length($0) && a[i++]= "\n" $0 : a[i++]=$0 }
{if(NR>1 && FNR==1) for(e=(i-c);e<=(i-1);e++) b[e]=d ;c=FNR; d=l }
{ if( length($0) > l) l=length($0)+1 } 
END{for(e=(i-c+1);e<=i;e++) b[e]=d; for(j=1;j<=i;j++) printf("%-"b[j]"s,",a[j-1] )}' infiles* >outfile


回答3:

#!/usr/bin/awk -f
function beginfile (file) {
    split("", a)
    max = 0
    delim = ""
}

function endfile (file) {
    for (i = 1; i <= lines; i++) {
        printf "%s%-*s", delim, max, a[i]
        delim = " ,"
    }
    printf "\n"
}

FILENAME != _oldfilename \
     {
         if (_oldfilename != "")
             endfile(_oldfilename)
         _oldfilename = FILENAME
         beginfile(FILENAME)
     }

     END   { endfile(FILENAME) }

{
    len = length($0)
    if (len > max) {
        max = len
    }
    a[FNR] = $0
    lines = FNR
}

To run it:

chmod u+x filename
./filename file1 file2

Note that in gawk you can do delete a instead of split("", a). GAWK 4 has builtin BEGINFILE and ENDFILE.