Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle an array where elements contain spaces in Bash?

Let's say I have a file named tmp.out that contains the following:

c:\My files\testing\more files\stuff\test.exe
c:\testing\files here\less files\less stuff\mytest.exe

I want to put the contents of that file into an array and I do it like so:

ARRAY=( `cat tmp.out` )

I then run this through a for loop like so

for i in ${ARRAY[@]};do echo ${i}; done

But the output ends up like this:

c:\My
files\testing\more
files\stuff\test.sas
c:\testing\files
here\less
files\less
stuff\mytest.sas

and I want the output to be:

c:\My files\testing\more files\stuff\test.exe
c:\testing\files here\less files\less stuff\mytest.exe

How can I resolve this?

like image 775
1lowlysysadm Avatar asked Dec 28 '25 04:12

1lowlysysadm


2 Answers

In order to iterate over the values in an array, you need to quote the array expansion to avoid word splitting:

for i in "${values[@]}"; do 

Of course, you should also quote the use of the value:

  echo "${i}"
done

That doesn't answer the question of how to get the lines of a file into an array in the first place. If you have bash 4.0, you can use the mapfile builtin:

mapfile -t values < tmp.out

Otherwise, you'd need to temporarily change the value of IFS to a single newline, or use a loop over the read builtin.

like image 110
rici Avatar answered Dec 30 '25 17:12

rici


You can use the IFS variable, the Internal Field Separator. Set it to empty string to split the contents on newlines only:

while IFS= read -r line ; do
    ARRAY+=("$line")
done < tmp.out

-r is needed to keep the literal backslashes.

like image 35
choroba Avatar answered Dec 30 '25 19:12

choroba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!