Define multiple variables in one row only

Asked

Viewed 377 times

3

I would like to parse a single line and break a string into several variables. In string which I will parse, the default is that each field is separated by a comma.

In several lines, the code to do what I want would be like this:

hostname=`echo $tripa | cut -d, -f1`
ip=`echo $tripa | cut -d, -f2`
serial=`echo $tripa | cut -d, -f3`

Is there a way to do this in only one line (without repeating the command cut several times, one for each variable)?

1 answer

1


I’m not sure it’ll work for your case.

tripa="meu host,127.0.0.1,abc"
IFS=',' read hostname ip serial <<<"$tripa"
echo -e "$hostname\n$ip\n$serial"

I found that answer here

  • 1

    It worked perfectly. I was still able to put inside a script and read the $tripa variable from the input of an external file: for tripa in $(cat $1 | cut -d, -F2,3,6); do IFS=',' read hostname ip serial <<"$tripa" echo -e "$hostname n$ip n$serial" done

Browser other questions tagged

You are not signed in. Login or sign up in order to post.