Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract fields to variable

Tags:

bash

I want to extract the fields from a line into variables:

aaa bbb ccc

'aaa' => $a, 'bbb' => $b, 'ccc' => $c. How to do it in bash?

I don't want to pipeline the processing, just need to extract them to variables or array.

like image 537
Dagang Avatar asked Jul 01 '11 03:07

Dagang


Video Answer


2 Answers

You can simply do:

read a b c <<<"aaa bbb ccc"

OUTPUT

$ echo "a=[$a] b=[$b] c=[$c]"
a=[aaa] b=[bbb] c=[ccc]

As per bash manual:

   Here Strings
       A variant of here documents, the format is:
              <<<word
       The word is expanded and supplied to the command on its standard input.
like image 61
anubhava Avatar answered Sep 24 '22 02:09

anubhava


The simplest is:

read a b c

with I/O redirection from where the line is being read:

while read a b c
do
    # Process
done < $some_file

If the data is already in a variable, then you could use:

read a b c < <(echo "$variable")

This uses a Bash-specific feature, process substitution.

like image 35
Jonathan Leffler Avatar answered Sep 24 '22 02:09

Jonathan Leffler