datacruncher
datacruncher

Reputation: 165

Merging awk and cut into one command

My line is:

var1="_source.statistics.test1=AAAAA;;;_source.statistics.test2=BBBB;;;_source.statistics.test3=CCCCC"

awk -F  ";;;" '{print $1}' <<<$var1 | cut -d= -f2
AAAAA
awk -F  ";;;" '{print $2}' <<<$var1 | cut -d= -f2
BBBB

How can I get to the same result using only AWK?

Upvotes: 0

Views: 128

Answers (3)

Ed Morton
Ed Morton

Reputation: 203684

Whenever you have name/tag=val input data it's useful to create an array of tag-value pairs so you can just print or do whatever else you like with the data by it's tags, e.g.:

$ awk -F';;;|=' '{for (i=1; i<NF; i+=2) f[$i]=$(i+1); print f["_source.statistics.test1"]}' <<<"$var1"
AAAAA

$ awk -F';;;|=' '{for (i=1; i<NF; i+=2) f[$i]=$(i+1); print f["_source.statistics.test3"], f["_source.statistics.test2"]}' <<<"$var1"
CCCCC BBBB

Upvotes: 1

tripleee
tripleee

Reputation: 189507

Awk lets you split a field on another delimiter.

awk -F  ";;;" '{split($1, a, /=/); print a[2] }'

However, perhaps a more fruitful approach would be to transform this horribly hostile input format to something a little bit more normal, and take it from there with standard tools.

sed 's/;;;/\
/g' inputfile | ...

Upvotes: 3

RavinderSingh13
RavinderSingh13

Reputation: 133538

Could you please try following, within single awk by making use of field separator -F setting it as either = or ; for each line passed to awk.

echo "$var1" | awk -F'=|;' '{print $2}'
AAAAA
echo "$var1" | awk -F'=|;' '{print $6}'
BBBB

OR

echo "$var1" | awk -F"=|;;;" '{print $2}'
AAAAA
echo "$var1" | awk -F"=|;;;" '{print $4}'
BBBB


Considering that you need these output for variables, if yes then you could use it by sed and placing its values in an array and later could make use of it. IMHO this is why arrays are built to save our time of creating N numbers of variables.

Creation of an array with sed:

array=( $(echo "$var1" | sed 's/\([^=]*\)=\([^;]*\)\([^=]*\)=\([^;]*\)\(.*\)/\2 \4/'  ) )

Creating of an array with awk:

array=( $(echo "$var1" | awk -F"=|;;;" '{print $2,$4}') )

Above will create an array with values of AAAAA and BBBB now to fetch it you could use.

for i in {0..1}; do echo "$i : ${array[$i]}"; done
0 : AAAAA
1 : BBBB

I have used for loop for your understanding of it, one could use directly array[0] for AAAAA or array[1] for BBBB.

Upvotes: 1

Related Questions