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 theeval
command to evaluate the line.Put the following into a file, say
parse.sh
, dochmod +x parse.sh
and run it with your input file as a parameter.Script
parse.sh
:File
input.txt
:Run:
Please note that the values must not have a space in them. E.g.
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 howeval
works: it just executes the given string.