Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading