Monday, November 1, 2021

[SOLVED] awk command to read a key value pair from a file

Issue

I have a file input.txt which stores information in KEY:VALUE form. I'm trying to read GOOGLE_URL from this input.txt which prints only http because the seperator is :. What is the problem with my grep command and how should I print the entire URL.

SCRIPT

$> cat script.sh
#!/bin/bash
URL=`grep -e '\bGOOGLE_URL\b' input.txt | awk -F: '{print $2}'`
printf " $URL \n"

INPUT_FILE

$> cat input.txt
GOOGLE_URL:https://www.google.com/

OUTPUT

https

DESIRED_OUTPUT

https://www.google.com/

Solution

Since there are multiple : in your input, getting $2 will not work in awk because it will just give you 2nd field. You actually need an equivalent of cut -d: -f2- but you also need to check key name that comes before first :.

This awk should work for you:

awk -F: '$1 == "GOOGLE_URL" {sub(/^[^:]+:/, "");  print}' input.txt

https://www.google.com/

Or this non-regex awk approach that allows you to pass key name from command line:

awk -F: -v k='GOOGLE_URL' '$1==k{print substr($0, length(k FS)+1)}' input.txt

Or using gnu-grep:

grep -oP '^GOOGLE_URL:\K.+' input.txt

https://www.google.com/


Answered By - anubhava