Reputation: 13
I'm a newbie with very small and specific needs. I'm using awk to parse something and I need to generate uninterrupted lines of text assembled from several pieces in the original text. But awk inserts a newline in the output whenever I use a semicolon.
Simplest example of what I mean:
Original text:
1 2
awk command:
{ print $1; print $2 }
The output will be:
1
2
The thing is that I need the output to be a single line, and I also need to use the semicolons, because I have to do multiple actions on the original text, not all of them print.
Also, using ORS=" " causes a whole lot of different problems, so it's not an option.
Is there any other way that I can have multiple actions in the same line without newline insertion?
Thanks!
Upvotes: 1
Views: 5300
Reputation: 204311
The newlines in the output are nothing to do with you using semicolons to separate statements in your script, they are because print
outputs the arguments you give it followed by the contents of ORS
and the default value of ORS
is newline.
You may want some version of either of these:
$ echo '1 2' | awk '{printf "%s ", $1; printf "%s ", $2; print ""}'
1 2
$
$ echo '1 2' | awk -v ORS=' ' '{print $1; print $2; print "\n"}'
1 2
$
$ echo '1 2' | awk -v ORS= '{print $1; print " "; print $2; print "\n"}'
1 2
$
but it's hard to say without knowing more about what you're trying to do.
At least scan through the book Effective Awk Programming, 4th Edition, by Arnold Robbins to get some understanding of the basics before trying to program in awk or you're going to waste a lot of your time and learn a lot of bad habits first.
Upvotes: 5
Reputation: 84423
You're getting newlines because print
sends OFS to standard output after each print statement. You can format the output in a variety of other ways, but the key is generally to invoke only a single print
or printf
statement regardless of how many fields or values you want to print.
One way to do this is to use a single call to print
using commas to separate arguments. This will insert OFS between the printed arguments. For example:
$ echo '1 2' | awk '{print $1, $2}'
1 2
If you don't want any separation in your output, just pass all the arguments to a single print
statement. For example:
$ echo '1 2' | awk '{print $1 $2}'
12
If you want more control than that, use formatted strings using printf
. For example:
$ echo '1 2' | awk '{printf "%s...%s\n", $1, $2}'
1...2
Upvotes: 0
Reputation: 23870
You have better control of the output if you use printf
, e.g.
awk '{ printf "%s %s\n",$1,$2 }'
Upvotes: 0