MirrG
MirrG

Reputation: 406

awk FS is a regular expression

My problem is the inability to output the treated file with the FS set as a regular expression. I have a file that I have to treat:

id 1:1 2:1 3:2 5:1
id 1:2 3:1 4:1

Where I want to multiply a value (after ':') by 2:

id 1:2 2:2 3:4 5:2
id 1:4 3:2 4:2

I tried :

awk 'BEGIN {FS=" [[:digit:]]+:"}{OFS=FS}{for (i=2; i<=NR;i++) $i=$i*2; print}' file

However, it gives me the literal [[:digit:]]+: as the FS. I red a similar question here and tried to set fields as records, printing $0, RT at the end, but it also didn't work.

Thanks for any tips.

Upvotes: 1

Views: 267

Answers (2)

jas
jas

Reputation: 10865

With gawk you can capture the field separators (analogous to RT) in the gawk-only extra argument to the split function:

BEGIN {FS=" [[:digit:]]+:"}

{
    split($0,a,FS,seps);
    printf "%s", a[1];
    for (i=2; i<=length(a); ++i)
      {printf "%s%s", seps[i-1], a[i]*2}
    print ""
}

$ awk -f mirr.awk mirr.txt
id 1:2 2:2 3:4 5:2
id 1:4 3:2 4:2

Upvotes: 2

Sundeep
Sundeep

Reputation: 23667

You can use split function

$ awk '{for(i=2; i<=NF; i++){split($i,a,":"); a[2]*=2; $i=a[1]":"a[2]}} 1' file
id 1:2 2:2 3:4 5:2
id 1:4 3:2 4:2


Or a simpler perl solution, where all numbers after : are multiplied by 2

$ perl -pe 's/:\K\d+/$&*2/ge' file
id 1:2 2:2 3:4 5:2
id 1:4 3:2 4:2

Upvotes: 4

Related Questions