6

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)

2 Answers 2

9

The builtin read command can assign to multiple variables:

IFS=, read _ _ _ var1 var2 var3 _ <<< "$LINE"
Sign up to request clarification or add additional context in comments.

1 Comment

Definitely the best answer, except that you assumed that there are only 6 fields. Maybe read _ _ _ var1 var2 var3 _ would be more appropriate?
4

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\""}' ) )

2 Comments

Yup just what I was looking for. Didn't know the ( $LINE ) thing changed everything to an array. Thanks.
This is a bad answer. Don't wordsplit command substitution output. Also, it won't work to begin with due to incorrect assignment syntax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.