help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Array Expansion


From: Andy Chu
Subject: Re: [Help-bash] Array Expansion
Date: Sun, 25 Jun 2017 13:03:59 -0700

Two ideas:

1) Use something like:

find -print0 | while read -d '' line; do echo $line; done

read -d '' splits on NUL terminators (this was discussed a few months ago).

'shopt -s lastpipe' or using a subshell might be useful if you want the
while loop state to persist after the pipeline.

If you really need to populate an array rather than just doing things in
the loop body, you'll need one of those.

Example of subshell:

find -print0 | (i=0; while read -d '' line; do echo $line; ((i++)); done;
echo $i )

Hm I can't get lastpipe to work for 'while loop', maybe it only works for
simple builtins like 'read' ?

$ shopt -s lastpipe; i=0; find -print0 | while read -d '' line; do echo
$line; ((i++)); done; echo
$i;
0  # was expecting non-zero


2) If your filenames contain spaces, but not newlines, set IFS=$'\n', and
then $(find ...) should split the paths correctly.


Andy



On Sun, Jun 25, 2017 at 12:25 PM, J.B. <address@hidden> wrote:

> Expanding an array for use in a for-loop behaves differently depending on
> how the array was created. How can I get bash to expand using a different
> delimiter? I tried `find -print0' after setting IFS= but bash just ignores
> it (and says so). I then tried `find -exec ls 
> --quoting-style=shell-escape-always',
> but that didn't work either.
>
> $ !find
> find ./path/ -type f -name \*.txt
> ./path/filename with spaces.txt
> ./path/good_filename.txt
>
> $ listoffiles=($(find ./path/ -type f -exec ls
> --quoting-style=shell-escape-always '{}' \;))
>
> $ echo address@hidden
> './path/filename with spaces.txt' './path/good_filename.txt'
>
> $ for file in  address@hidden; do echo $file; done
> './path/filename
> with
> spaces.txt'
> './path/good_filename.txt'
>
> $ for file in "address@hidden"; do echo $file; done
> './path/filename
> with
> spaces.txt'
> './path/good_filename.txt'
>
> $ for file in "${listoffiles[*]}"; do echo $file; done
> './path/filename with spaces.txt' './path/good_filename.txt'
>
> $ !unse
> unset -v listoffiles
>
> $ listoffiles=(
> > './path/filename with spaces.txt'
> > './path/good_filename.txt'
> > )
>
> $ for file in address@hidden; do echo $file; done
> ./path/filename
> with
> spaces.txt
> ./path/good_filename.txt
>
> $ for file in "address@hidden"; do echo $file; done
> ./path/filename with spaces.txt
> ./path/good_filename.txt
>
>
>


reply via email to

[Prev in Thread] Current Thread [Next in Thread]