Ridalgo
Ridalgo

Reputation: 711

using awk to perform operation on second value, only on lines with a specific string

ok. i have this which works. yay!

awk '/string/ { print $0 }' file1.csv | awk '$2=$2+(int(rand()*10))' > file2.csv

but i want the context of my file also printed into file2.csv. this program only prints the lines which contain my string, which is good, it's a start.

i would, but, i can't simply apply the operation to the $2 values on every line because the values of $2 on lines that don't contain my string, are not to be changed.

so, i want the original (file1.csv) contents intact with the only difference being an adjusted value at $2 on lines matching my string.

can someone help me? thank you.

And here are 4 lines from the original csv:

2, 0, Control, 0, 7, 1000  
2, 0, Control, 0, 10, 540  
2, 30720, String, 0, 76, 100  
2, 32620, String, 0, 76, 0

Expected output is the same aside from small variations to $2:

2, 0, Control, 0, 7, 1000  
2, 0, Control, 0, 10, 540  
2, 30725, String, 0, 76, 100  
2, 32621, String, 0, 76, 0

Upvotes: 0

Views: 78

Answers (2)

James Brown
James Brown

Reputation: 37464

Something like this, maybe:

$ awk -F", " -v OFS=", " '$3 ~ /String/ { $2=$2+(int(rand()*10))} { print $0 }' file1.csv
2, 0, Control, 0, 7, 1000  
2, 0, Control, 0, 10, 540  
2, 30722, String, 0, 76, 100  
2, 32622, String, 0, 76, 0

Upvotes: 1

karakfa
karakfa

Reputation: 67547

$ awk 'BEGIN{FS=OFS=", "} /String/{$2+=int(rand()*10)}1' file

2, 0, Control, 0, 7, 1000
2, 0, Control, 0, 10, 540
2, 30722, String, 0, 76, 100
2, 32622, String, 0, 76, 0

you probably need to initialize the rand seed in the BEGIN block as well, otherwise you'll always get the same rand sequence.

Upvotes: 2

Related Questions