LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How to change the delimiter when I do a "${myarray[@]}" in Bash? (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-change-the-delimiter-when-i-do-a-%24%7Bmyarray%5B%40%5D%7D-in-bash-4175459613/)

user1x 04-25-2013 08:48 PM

How to change the delimiter when I do a "${myarray[@]}" in Bash?
 
I have an array of file paths that I want to process with a single command. Some of the filenames have a space. So I can't do this:

echo "${myarray[@]}"|xargs myoperation

I'd like to use `xargs -0` but I can't figure out how to make the output of the array delimited by a null character instead of a space. Any ideas?

grail 04-25-2013 11:20 PM

Try looking up the IFS variable.

user1x 04-26-2013 07:05 AM

IFS doesn't seem to help:
x=("a" "b 2" "c");IFS=$'\0' echo "${x[@]}"|xxd

gives me:
0000000: 6120 6220 3220 630a a b 2 c.

Maybe I'm just using it wrong? This is in Ubuntu 12 by the way.

chrism01 04-26-2013 08:16 AM

Here's a short example
Code:

a=(a "b 2" c)
for i in "${a[@]}"
do
        echo $i
done

# output
a
b 2
c


Kenhelm 04-26-2013 08:48 AM

printf can insert the null character after each array element.
Code:

printf '%s\0' "${myarray[@]}" | xargs -0 myoperation

millgates 04-26-2013 09:58 AM

Quote:

Originally Posted by user1x (Post 4938974)
I have an array of file paths that I want to process with a single command. Some of the filenames have a space. So I can't do this:

echo "${myarray[@]}"|xargs myoperation

I'd like to use `xargs -0` but I can't figure out how to make the output of the array delimited by a null character instead of a space. Any ideas?

Maybe I misunderstood your question, but why don't you just do

Code:

myoperation "${myarray[@]}"

user1x 04-26-2013 01:04 PM

Quote:

Originally Posted by millgates (Post 4939328)
Maybe I misunderstood your question, but why don't you just do

Code:

myoperation "${myarray[@]}"

Good question. I have potentially thousands of files. It will have an command line limit overflow.

user1x 04-26-2013 01:06 PM

Quote:

Originally Posted by Kenhelm (Post 4939297)
printf can insert the null character after each array element.
Code:

printf '%s\0' "${myarray[@]}" | xargs -0 myoperation

Perfect. That will work!

x=("a" "b 2" "c");printf '%s\0' "${x[@]}"|xxd

gives me:
0000000: 6100 6220 3200 6300 a.b 2.c.

David the H. 04-29-2013 09:28 AM

I agree that printf+xargs is generally the way to go, but another option would be to splice the array with a c-style for loop, to limit the number of entries processed at once.

Code:

for (( i=0; i<${#array[@]} ; i+=50 )); do

    mycommand "${array[@]:i:50}"

done

This will run the command on 50 entries at a time.


All times are GMT -5. The time now is 02:38 AM.