Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk line break with printf

Tags:

shell

awk

db2

I have a simple shell script, shown below, and I want to put a line break after each line returned by it.

#!/bin/bash
vcount=`db2 connect to db_lexus > /dev/null; db2 list tablespaces | grep -i "Tablespace ID" | wc -l`
db2pd -d db_lexus -tablespaces | grep -i "Tablespace Statistics" -A $vcount | awk '{printf ($2 $7)}'

The output is:

Statistics:IdFreePgs0537610230083224460850d

and I want the output to be something like that:

Statistics:
Id FreePgs
0 5376
1 0
2 3008
3 224
4 608
5 0

Is that possible to do with shell scripting?

like image 435
Walter WF Avatar asked Mar 14 '23 12:03

Walter WF


2 Answers

Your problem can be reduced to the following:

$ cat infile
11 12
21 22
$ awk '{ printf ($1 $2) }' infile
11122122

printf is for formatted printing. I'm not even sure if the behaviour of above usage is defined, but it's not how it's meant to be done. Consider:

$ awk '{ printf ("%d %d\n", $1, $2) }' infile
11 12
21 22

"%d %d\n" is an expression that describes how to format the output: "a decimal integer, a space, a decimal integer and a newline", followed by the numbers that go where the %d are. printf is very flexible, see the manual for what it can do.

In this case, we don't really need the power of printf, we can just use print:

$ awk '{ print $1, $2 }' infile
11 12
21 22

This prints the first and second field, separated by a space1 – and print does add a newline without us telling it to.

1More precisely, "separated by the value of the output field separator OFS", which defaults to a space and is printed wherever we use , between two arguments. Forgetting the comma is a popular mistake that leads to no space between the record fields.

like image 118
Benjamin W. Avatar answered Mar 24 '23 14:03

Benjamin W.


It looks like you just want to print columns 2 and 7 of whatever is passed to AWK. Try changing your AWK command to

    awk '{print $2, $7}'

This will also add a line break at the end.

like image 38
e0k Avatar answered Mar 24 '23 15:03

e0k