3

Im confused with how the following cut works in the bash script.

Sample of file.csv:

#10.10.10.10;28;9.10.10.10: up;Something ;More random spaces

My script:

#!/bin/bash

csv_file="file.csv"

locations=( $( cut -d';' -f5 $csv_file ) )

for ((i=0; i < ${#locations[@]}; i++))
do
   echo "${locations[$i]}"
done

The result of the script is:

More
random
spaces

When I just copy and paste the cut in my CLI without any echos or variables the cut works as I´d expect and prints:

More random spaces

I am sure it´s some bracket or quote problem, but I just can't figure it out.

1
  • Why are you saving it to an array if you want the whole string?
    – 123
    Commented Jun 15, 2016 at 14:03

4 Answers 4

4

Your command substitution $(...) undergo's word splitting and pathname expansion:

a="hello world"
arr=($(echo "$a")); # Bad example, as it could have been: arr=($a)

echo "${arr[0]}" # hello
echo "${arr[1]}" # world

You can prevent this by wrapping the command substitution in double quotes:

arr=( "$(...)" )
echo "${arr[0]}" # hello world

Same applies to parameter expansions, eg:

a="hello world"
printf "<%s>" $a   # <hello><world>
printf "<%s>" "$a" # <hello world>
1

You need to quote the subshell command in the locations array:

locations=( "$( cut -d';' -f5 $csv_file )" )

More on the matter "arrays with spaces" here: BASH array with spaces in elements

0

The following statement creates an array of three elements:

location=(More random spaces)
0

Your cut command gives the string More random spaces, and when you convert that to an array it has 3 fields.

You can change your script into

cut -d";" -f5 < ${csv_file}

When you want to do some more with each line of output, you have more control with

csv_file="file.csv"

while IFS=";" read -r f1 f2 f3 f4 f5 f6_and_higher; do
   # Ignore fields f1 f2 f3 and f4
   echo "${f5}"
done < ${csv_file}

or (better) you can avoid the while loop with

awk -F ";" '{print $5}' ${csv_file}

Not the answer you're looking for? Browse other questions tagged or ask your own question.