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.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
whateverrest
  • 178
  • 3
  • 11

4 Answers4

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>
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
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

Community
  • 1
  • 1
T. Kuther
  • 610
  • 3
  • 7
0

The following statement creates an array of three elements:

location=(More random spaces)
choroba
  • 231,213
  • 25
  • 204
  • 289
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}
Walter A
  • 19,067
  • 2
  • 23
  • 43