LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   awk gsub() command - string (column) manipulation - substitution (https://www.linuxquestions.org/questions/linux-newbie-8/awk-gsub-command-string-column-manipulation-substitution-793870/)

casperdaghost 03-07-2010 10:30 PM

awk gsub() command - string (column) manipulation - substitution
 
i use this script to get the time and date of back and fourth transactions for a particular execution id. I use a substr command on the 5th column to to cut the milli seconds off the time value. - otherwise the times would look like 08:30:04.235

grep <executionID> <auditfile> | awk '{ print $1, $2, $3, $4, substr($5,1,8}

FIX -> Mon 3/1/2010 08:30:04
FIX <- Mon 3/1/2010 08:32:36
FIX <- Mon 3/1/2010 08:35:08
FIX -> Mon 3/1/2010 08:35:27
FIX <- Mon 3/1/2010 08:37:02
FIX <- Mon 3/1/2010 08:39:37
FIX -> Mon 3/1/2010 08:39:42

anyhow - i append two sed commands to further clarify the direction of the message.

awk '{ print $1, $2, $3, $4, substr($5,1,8} | sed -e 's/->/ ->IN/g' | sed -e 's/<-/<-OUT/g'

FIX -> IN Mon 3/1/2010 08:30:04
FIX <- OUT Mon 3/1/2010 08:32:36
FIX <- OUT Mon 3/1/2010 08:35:08
FIX -> IN Mon 3/1/2010 08:35:27
FIX <- OUT Mon 3/1/2010 08:37:02
FIX <- OUT Mon 3/1/2010 08:39:37
FIX -> IN Mon 3/1/2010 08:39:42

I tried using an awk gsub () command within the string instead of the two seds, but it did not work:
awk '{ print gsub(/<regex>/, <replace with>,$1), $2, $3, $4, substr($5,1,8}

the sed works ok, but it would be cooler to make the replacement within the awk command:

gsub(/->/,-> IN, $1)

Is there a way where i could replace the value of the $1 column in the awk print string?

Tinkster 03-08-2010 02:12 AM

Your problem is that you're trying to use gsub in the print
statement. You can do two things:
a) use gensub instead of gsub
Code:

$ awk '{print gensub( /<-/, "<- OUT", "g", gensub( /->/ , "-> IN","g"))}' ghost
FIX -> IN Mon 3/1/2010 08:30:04
FIX <- OUT Mon 3/1/2010 08:32:36
FIX <- OUT Mon 3/1/2010 08:35:08
FIX -> IN Mon 3/1/2010 08:35:27
FIX <- OUT Mon 3/1/2010 08:37:02
FIX <- OUT Mon 3/1/2010 08:39:37
FIX -> IN Mon 3/1/2010 08:39:42

b) separate gsub from print.
Code:

awk '{gsub( /->/ , "-> IN");gsub( /<-/ , "-> OUT");print}' ghost
FIX -> IN Mon 3/1/2010 08:30:04
FIX -> OUT Mon 3/1/2010 08:32:36
FIX -> OUT Mon 3/1/2010 08:35:08
FIX -> IN Mon 3/1/2010 08:35:27
FIX -> OUT Mon 3/1/2010 08:37:02
FIX -> OUT Mon 3/1/2010 08:39:37
FIX -> IN Mon 3/1/2010 08:39:42

In this case I'd prefer b) - it's cleaner & shorter.


Cheers,
Tink


All times are GMT -5. The time now is 09:22 PM.