Ubuntu – How to get values after an equal sign

bashtext processing

I have a file delimited with space and random column ordering as follows:

name=Joan age=42 ip=172.20.1.80 sex=M loc=UK 
loc=IR sex=F ip=172.20.1.1 age=32 name=Sandra 

I want to extract specific fields (name, loc, and ip) only.

So the result that I'm looking for is as follows:

Joan|UK|172.20.1.80
Sandra|IR|172.20.1.1

Best Answer

Luckily, your input file has a format the shell understands when it comes to assigning variables a value: var1=value1 var2=value2 etc. So we can simply read each line and use the eval command to evaluate the line.

Put the following into a file, say parse.sh, do chmod +x parse.sh and run it with your input file as a parameter.

Script parse.sh:

#!/usr/bin/env bash

while read line; do
    eval $line;
    echo "$name|$loc|$ip"
done < "$1"

exit 0;

File input.txt:

name=Joan age=42 ip=172.20.1.80 sex=M loc=UK
loc=IR sex=F ip=172.20.1.1 age=32 name=Sandra

Run:

me@ubuntu:~> ./parse.sh input.txt 
Joan|UK|172.20.1.80
Sandra|IR|172.20.1.1

Please note that the values must not have a space in them. E.g.

ip=... name=Ubai salih loc=...

would not work and give syntax errors. Also, if the input file would contain a line with a bad_command that command gets executed because that is how eval works: it just executes the given string.

Related Question