LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   BASH: How can I get an array with ls-output containing blanks? (https://www.linuxquestions.org/questions/programming-9/bash-how-can-i-get-an-array-with-ls-output-containing-blanks-4175594848/)

ernstlx 12-05-2016 01:47 PM

BASH: How can I get an array with ls-output containing blanks?
 
Hello!

I like to get an array with every path containing a file ".tag" in the sub-subdirectory:

Code:

TAGPATH="*/*/.tag"
INDX=(`ls -Q $TAGPATH`)

The path to the files contains blanks and this is reason why it fails. I get an array, but regardless of the quotation (single, double or none) it results in array elements only from one blank to the next.

I've tried every ls option I know, tried to manipulate the output with sed to escape the blank characters, but neither helped. Without blanks it's no problem, but with blanks it seems to be impossible.

Can someone help me solving this problem?

Thanks in advance!

szboardstretcher 12-05-2016 02:05 PM

If you were to get the paths into an array, you would be able to do this:

Code:

PATHS=("/tmp/what ever/this1"
      "/tmp/what ever/this2"
      "/tmp/what ever/this3"
      "/tmp/what ever/this4")
IFS=""
for p in ${PATHS[*]}
do
    echo "${p}"
done

Is that what you are looking for?

Edit: Or, now that I'm re-reading it, are you looking for how to get the paths into the array in the first place?

If so, just use IFS to call out \n\t as field seperators, and ignore spaces, while you are importing it into the array.

Code:

IFS=$'\t\n'
TAGPATH="*/*/.tag"
INDX=(`ls -Q $TAGPATH`)


ernstlx 12-05-2016 02:20 PM

$IFS does the trick!

Thank you very much!!!

Greetings from Vienna!
Ernst

rknichols 12-06-2016 09:06 AM

It's a lot easier if you don't use ls:
Code:

TAGPATH="*/*/.tag"
INDX=($TAGPATH)

Pathname expansion occurs after word splitting, so embedded spaces in the names are taken literally and not as word separators.

It is almost always a bad idea to process the output from ls. That output is primarily intended for human consumption.

Fat_Elvis 12-10-2016 09:31 AM

Quote:

Originally Posted by rknichols (Post 5638638)
It's a lot easier if you don't use ls:
Code:

TAGPATH="*/*/.tag"
INDX=($TAGPATH)

Pathname expansion occurs after word splitting, so embedded spaces in the names are taken literally and not as word separators.

It is almost always a bad idea to process the output from ls. That output is primarily intended for human consumption.

Oh wow. This is actually very useful info. Thanks.


All times are GMT -5. The time now is 09:43 PM.