Yoann Pageaud
Yoann Pageaud

Reputation: 519

Awk Printf result of a subtraction between column and fixed value

Let's say I have:

David    1500     2338    Baker
Danny    1290     1550    Bold
Domminic    25     28    Baker

So there are 4 tab-separated columns. size of all columns can vary a lot. What I would like is a solution using awk printf to do : $2 - 1 for each line. Here is the result I would like:

David    1499     2338    Baker
Danny    1289     1550    Bold
Domminic    24     28    Baker

And Finally here is what I have done so far:

awk '{if($0 ~/^D/) \
    {printf ("%s\t%d\t%d\t%s\n",$1,($2 - 1),$3,$4)}}'

Obviously if I am asking this question, it's because I do not get the expected result. This is what I obtain:

David    1500-1     2338    Baker
Danny    1290-1     1550    Bold
Domminic    25-1     28    Baker

I tried other stuff but it did not worked better...It is really important to me to get a solution in awk with printf. "help me obi wan kenobi you're my only hope"!

Edit: I made a little mistake in the printf "format" part, the last \t should be a \n . And then the problem is solved I don't understand why I get this error before. Big thank to Ed for the help (see comment). The awk command is now working.

Upvotes: 0

Views: 536

Answers (2)

Inian
Inian

Reputation: 85560

Just make it simpler by setting input and output field separators to Tab and modify the $2 value as

awk 'BEGIN{FS=OFS="\t"}{$2=$2-1}1' file

You don't need printf at all here. Once the field separators are set, the individual fields can be accessed as $1..$NF. Since the value we are concerned is in $2, just subtract one from it.

The default print action (implied by always-true pattern 1) will rebuild the output line from the fields based on the output field separator (OFS) set.
Since we are modifying only $2 here, the other fields remain intact.

Upvotes: 3

karakfa
karakfa

Reputation: 67467

here is another awk

$ awk '/^D/{$2--}1' file | column -t

David     1499  2338  Baker
Danny     1289  1550  Bold
Domminic  24    28    Baker

or, add BEGIN{FS=OFS="\t"} for tabular in/out.

Upvotes: 2

Related Questions