linuxbashawk

Exclude the last character when printing in a for loop


I am using linux and trying to code a loop which can take in variables and concatenates them into an equation. But how do I remove it for the last loop.

printf "(%s + %s) x ", $1, $2

I want to print (1 + 1) x (2 + 2) x (3 + 3), but instead I get (1 + 1) x (2 + 2) x (3 + 3) x

What should I do to exclude this last "x"?


Solution

  • This is probably what you're trying to do:

    $ awk '{printf "%s(%s + %s)", sep, $1, $2; sep=" x "} END{print ""}' file
    (1 + 1) x (2 + 2) x (3 + 3)
    

    That was run against an input file created by:

    $ printf '%d %d\n' 1 1 2 2 3 3
    1 1
    2 2
    3 3
    
    $ printf '%d %d\n' 1 1 2 2 3 3 > file