0

Need a script to iterate through below file to read keys, values and extract values eg. foo_key1, foo.com, /tmp/worker${Build_Number} out of key and values assign them to another variable (eg. A="foo_key1", B="foo.com", C="/tmp/worker${Build_Number}").

cat abc.txt

foo_key1=foo.com|/tmp/worker${Build_Number}
foo_key2=goo.com|/tmp/manager${Build_Number}

I have tried the below code but no luck.

while IFS== read -r key val ; do
    val=${val%\"}; val=${val#\"}; key=${key#export };
    A="$(cut -d'_' -f1 <<<"$key")"
    B="$(cut -d'_' -f1 <<<"$val")"
    C="$(cut -d'_' -f2 <<<"$val")"
    echo $A
    echo $B
    echo $C
  done < abc.txt

Expected output:

foo_key1 
foo.com
/tmp/worker${Build_Number}
1

Simply use awk to split on = or | and print the 3 columns, then use read to assign the columns to variables

awk -F '[=|]' '{print $1, $2, $3}' abc.txt | while read A B C; do
    echo $A
    echo $B
    echo $C
done

Also you can add a regular expression befor the curly braces to filter the data, for example '/\S+/ {print $1, $2, $3}' this uses a regular expression that will match more than 1 character that is not a whitespace thus skipping blank lines

1

You can try :

while IFS='|=' read A B C ; do
  echo "$A"
  echo "$B"
  echo "$C"
done < abc.txt
0

Your code would benefit from these revisions:

#!/bin/bash

cat abc.txt | while IFS= read -r line ; do

A=$(echo $line | sed -e 's/=/ /g;s/|/ /g' |  awk '{print $1}')
B=$(echo $line | sed -e 's/=/ /g;s/|/ /g' |  awk '{print $2}')
C=$(echo $line | sed -e 's/=/ /g;s/|/ /g' |  awk '{print $3}')

    echo $A
    echo $B
    echo $C
  done

foo_key1
foo.com
/tmp/worker${Build_Number}
foo_key2
goo.com
/tmp/manager${Build_Number}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.