Unix [SOLVED]: printf format specifiers in awk does not work for multiple parameters

Unix [SOLVED]: printf format specifiers in awk does not work for multiple parameters

Home Forums Unix Unix [SOLVED]: printf format specifiers in awk does not work for multiple parameters

Tagged: , , , ,

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #37034

    Anonymous

    QuestionQuestion

    I’m trying to Write a program script in Bash named example7
    Which accepts as parameters: a file name (lets call it file 1) and a list of
    Numbers (below we’ll call it List 1) and what the program needs to do is to print as output the columns from
    File 1 after rescheduling them to right or left by the numbers in list 1. (This is obtainable by using the printf command of awk).

    Example

    Suppose the contents of an F1 file are:

    A abcd ddd eee zz tt
    ab gggwe 12 88 iii jjj
    yaara yyzz 12abcd xyz x y z
    

    After running the program by command:

    example7 F1 -8 -7 6 4
    

    Output:

    A       abcd      ddd eee
    ab      gggwe      12 88
    yaara   yyzz   12abcd xyz
    

    In the example above between A and ABCD there are 7 spaces, between abcd and ddd
    there are 6 spaces and between ddd and eee
    there is one space.

    Another example:

    After running the program by command:

    example7 F1 -8 -7 6 4 5
    

    Output:

    A       abcd      ddd eee   zz
    ab      gggwe      12  88  iii
    yaara   yyzz   12abcd xyz    x
    

    In the example above between A and ABCD there are 7 spaces, between abcd and ddd
    there are 6 spaces, between ddd and eee
    there is one space, between eee and zz there are 3 spaces, between 88 and iii
    there are two spaces, between xyz and x there are 4 spaces.

    I’ve tried doing something like this:

    file=$1
    shift
    awk '{printf "%'$1'sn" ,$1}' $file
    

    but it only works for one number and one parameter and I don’t know how I can do it for multiple columns and multiple parameters..
    any help will be appreciated.

    #37035

    Anonymous

    Accepted AnswerAnswer

    Set an awk variable to all the remaining parameters, then split it and loop over them.

    file=$1
    shift
    awk -v sizes="$*" '{words = split(sizes, s); for(i = 1; i <= words; i++) printf("%" s[i] "s", $i); print ""; }' "$file"
    

    It’s generally wrong to try to substitute a shell variable directly into an awk script. You should prefer to set an awk variable using -v, and then use awk‘s own string concatenation operation, as I did with s[i].

    Source: https://stackoverflow.com/questions/48020952/printf-format-specifiers-in-awk-does-not-work-for-multiple-parameters
    Author: Barmar
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.