saccharine
saccharine

Reputation: 904

Combine multiple cut commands into variable assignations into one cut command

Given a previously defined $LINE in a shell script, I do the following

var1=$(echo $LINE | cut -d, -f4)
var2=$(echo $LINE | cut -d, -f5)
var3=$(echo $LINE | cut -d, -f6)

Is there any way for me to combine it into one command, where the cut is run only once? Something like

var1,var2,var3=$(echo $LINE | cut -d, -f4,5,6)

Upvotes: 6

Views: 5417

Answers (2)

glenn jackman
glenn jackman

Reputation: 246827

The builtin read command can assign to multiple variables:

IFS=, read _ _ _ var1 var2 var3 _ <<< "$LINE"

Upvotes: 9

zebediah49
zebediah49

Reputation: 7611

yes, if you're ok with arrays:

var= ( $(echo $LINE | cut -d, --output-delimiter=' ' -f4-6) )

Note that that make var 0-indexed.

Though it might just be quicker and easier to turn the CSV $LINE into something that bash parenthesis understand, and then just do var = ( $LINE ).

EDIT: The above will cause issues if you have spaces in your $LINE... if so, you need to be a bit more careful, and AWK might be a better choice to add quotes:

var= ( $( echo $LINE | awk IFS=, '{print "\"$4\" \"$5\" \"$6\""}' ) )

Upvotes: 4

Related Questions