Rabi Siddique
244 words
1 minutes
My First UseCase of the AWK Command
2024-07-22

f I’ve recently had my first use case of the awk command. I’ve heard of it for quite some time but never actually made use of it. So recently, in a CI pipeline I was working on, I needed to extract a specific value from the logs. I needed this value so that I can use in my next workflow. The logs looked like this:

2024-07-18T10:16:32.219199Z  INFO ThreadId(01) 🎊  agoric-emerynet-8 => OpenAckChannel(OpenAck { port_id: transfer, channel_id: channel-51, connection_id: connection-56, counterparty_port_id: transfer, counterparty_channel_id: channel-42 }) at height 8-6169510

My job was to extract the channel_id from these logs. That’s where I came across the awk command. Here’s what I did:

awk -F 'channel_id:' '{print $2}' | awk -F ',' '{print $1}'

So this is what is happening: using the -F flag, I pass a separator to the awk command. By default, it uses a space as a separator, but I gave it a different separator, channel_id:. Now awk will split the log line around this separator. It will split the line into two parts, and I will extract the second part as indicated by print $2. The second part contains the channel_id and will look something like this:

 channel-51, connection_id: connection-56, counterparty_port_id: transfer, counterparty_

Then, by piping this output to the second awk, I give a different separator, which is the , this time. It will split the line wherever it encounters ,. When executing the second awk, I can print $1 to extract the channel id, which will be:

channel-51
My First UseCase of the AWK Command
https://rabisiddique.com/posts/the-awk-command/
Author
Rabi Siddique
Published at
2024-07-22