awk line break after each file

前端 未结 3 1444
隐瞒了意图╮
隐瞒了意图╮ 2021-01-28 15:12

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?



        
相关标签:
3条回答
  • 2021-01-28 15:31

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

    0 讨论(0)
  • 2021-01-28 15:35
    #!/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.

    0 讨论(0)
  • 2021-01-28 15:41

    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
    
    0 讨论(0)
提交回复
热议问题