azes
azes

Reputation: 13

Awk - replacement with seperators

i wrote this awk-Program

awk '{x=$2-5; print $1, x, $3}' 

which reduces the second number in each line by 5.

This works perfectly fine, when the input is like this: number1 number2 number3 (i.e. seperated by spaces).The output is then number1 number2-5 number3.

Now, how can i extend that program to implement the same functionality if the numbers are seperated by ; instead of spaces - can anyone help me?

For example the input is

30;31;32
11;6;5
1;7;10

The expected output is then

30;26;32
11;1;5
1;2;10

Upvotes: 1

Views: 53

Answers (2)

RARE Kpop Manifesto
RARE Kpop Manifesto

Reputation: 2811

if you wanna be REALLY idiomatic awk ::

echo '30;31;32
11;6;5
1;7;10' | 

awk '($2-=5)_' FS=\; OFS=\;
                                  vs.
awk 'BEGIN{FS=OFS=";"} {$2-=5} 1'

30;26;32
11;1;5
1;2;10

The extra bit about ( )_ is to force a string concat with empty string, so zeros will still get printed out.

Upvotes: 0

dawg
dawg

Reputation: 103844

You are very close!

You just need to change the FS and OFS variables and awk will do the rest:

awk 'BEGIN{FS=OFS=";"}
{x=$2-5; print $1, x, $3}' file
30;26;32
11;1;5
1;2;10

Read about these variables in the awk manual.


As Ed Morton states in comments, you can also use more idiomatic awk if you know the input and output have the same number of fields:

awk 'BEGIN{FS=OFS=";"}
{$2-=5; print}' 

Or:

awk 'BEGIN{FS=OFS=";"}
{$2-=5} 1'    # the 1 is True and awk reacts to a true by printing

Upvotes: 1

Related Questions