Combining multiple cut commands into destination variables into a single cut command

Given the previously defined $ LINE in the 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 to combine it into one team where the cut is launched only once? Sort of

 var1,var2,var3=$(echo $LINE | cut -d, -f4,5,6) 
+4
source share
2 answers

yes if you are ok with arrays:

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

Note that make var 0-indexed.

Although it may be simpler and easier to turn CSV $LINE into something that the bash bracket understands, then just do var = ( $LINE ) .

EDIT: The above problems will cause problems if you have spaces in your $ LINE ... if so, you need to be a little more careful, and AWK might be the best choice for adding quotes:

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

The built-in read command can assign several variables:

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

All Articles