1753776 Members
7099 Online
108799 Solutions
New Discussion юеВ

Reg: awk

 
SOLVED
Go to solution
VEL_1
Valued Contributor

Reg: awk


Hello All,

The following awk command prints $1 and $2 variable without space. How can I include the space between two variables.

# echo "This is awk command" | awk 'BEGIN { print "BEGIN" } {print $1$2 ; print $3} END { print $4}'
BEGIN
Thisis
awk
command

Expected Output:

# echo "This is awk command" | awk 'BEGIN { print "BEGIN" } {print $1$2 ; print $3} END { print $4}'
BEGIN
This is
awk
command

Can someone solve my problem??
6 REPLIES 6
Biswajit Tripathy
Honored Contributor

Re: Reg: awk

Replace
print $1$2
with
printf ("%s %s", $1, $2);

Pretty much like C-language printf.

- Biswajit
:-)
Slawomir Gora
Honored Contributor

Re: Reg: awk

Hi,

for your example:
echo "This is awk command" | awk '{printf "BEGIN\n%s %s\n%s\n%s\n", $1,$2,$3,$4}'


Francisco J. Soler
Honored Contributor

Re: Reg: awk

Hi, you can try this:

echo "This is awk command" | awk 'BEGIN { print "BEGIN" } {space=" " ; print $1 space $2 ; print $3} END { print $4}'

It is not very elegant but works and does not add extra functionality

Frank.
Linux?. Yes, of course.
Stuart Browne
Honored Contributor
Solution

Re: Reg: awk

echo "This is awk command" | awk 'BEING { print "BEGIN" } { print $1,$2; print $3} END { print $4 }'

String concatenation when using print is quite interesting in 'awk'.

Whilst using 'print $1 $2;' works, it squishes things together. This is the same as if you use 'print $1.$2;'.

There have been a number of solutions above, but if you are wanting to only include one space, awk allows you to do this with a single comma ('print $1, $2;').

This should work on both GNU awk, as well as commercial unix awk's.
One long-haired git at your service...
Antoine Morpain
Occasional Advisor

Re: Reg: awk

Hello,

Would you need 2 spaces between $1 and $2 then one between $2 and $3, this also works:
...{print $1" "$2,$3}...

Have fun.
Antoine Morpain
Occasional Advisor

Re: Reg: awk

Hello webmaster and others,

Please note that the forum form removes multiple spaces in the strings; in the previous article there should be 2 spaces between the quotes: ..."\ \ "...

Regards.