Friday 11 October 2019

How to use awk to modify the file on Linux

Hi,

Am giving a sample use case here.

Say, there is a file called detectionData.csv which has data separated with pipe symbol ( | )

And, you wish to update the 5th column of all the records, you can use something like below:

cat detectionData.csv | awk 'BEGIN { OFS=FS="|" } { $5="PartyExtreme00003"; print }' > detectionDataNew3.csv

Now, say, you wish to do the above but only every 10th row and not all the rows, you can use something like below:

cat detectionData.csv | awk 'BEGIN { OFS=FS="|" } { if (NR % 10==1) {$5="PartyExtreme00001"}; print }' > detectionDataNew10.csv

And, now say, you wise to do for part of the file, say for the first 50000 records, you can use something like below:

cat detectionData_1L.csv | awk 'BEGIN { OFS=FS="|" } { if (NR < 50000) {$5="PartyExtreme00001"} else {$5="PartyExtreme00003"}; print }' > detectionData_1L_50_50.csv
Enjoy!

No comments:

Post a Comment