Monday 18 August 2008

awk: find a field and replace it

Sometimes you'll need to search for a specific field and replace it with something else here's some awk code written out as it would appear within a script:

# find a field and replace it - then print the first space delimited field.
/447782000913/ {
gsub(/447782000913/, $2)
}
{ print $1 }

Here's the same command written out in one line as we're used to:

awk '/447782000913/ {gsub(/447782000913/, $2) }{ print $1 }' file.txt

We're introduced to a new built-in function of awk that appears really useful but in reality I've actually only used it a couple of times - gsub().

What's happening in the command is that we're searching for a pattern match. Anything between two forward-slashes '/' is pattern matched. When this matched is made the gsub() command is carried out. This gsub() command takes the pattern between IT's two forward slashes and replaces it with what it finds in field two ($2).

No comments: