Need to process files in current directory one at a time. I am looking for a way to take the output of ls
or find
and store the resulting value as elements of an array. This way I can manipulate the array elements as needed.
to redirect the output of the ls command into a file called "ls. out" in your home directory. Remember that the tilde (~) is Unix shorthand for your home directory. In this command, the ls command will list the contents of the /tmp directory.
The ls command writes to standard output the contents of each specified Directory or the name of each specified File, along with any other information you ask for with the flags. If you do not specify a File or Directory, the ls command displays the contents of the current directory.
To answer your exact question, use the following:
arr=( $(find /path/to/toplevel/dir -type f) )
$ find . -type f ./test1.txt ./test2.txt ./test3.txt $ arr=( $(find . -type f) ) $ echo ${#arr[@]} 3 $ echo ${arr[@]} ./test1.txt ./test2.txt ./test3.txt $ echo ${arr[0]} ./test1.txt
However, if you just want to process files one at a time, you can either use find
's -exec
option if the script is somewhat simple, or you can do a loop over what find returns like so:
while IFS= read -r -d $'\0' file; do # stuff with "$file" here done < <(find /path/to/toplevel/dir -type f -print0)
for i in `ls`; do echo $i; done;
can't get simpler than that!
edit: hmm - as per Dennis Williamson's comment, it seems you can!
edit 2: although the OP specifically asks how to parse the output of ls
, I just wanted to point out that, as the commentators below have said, the correct answer is "you don't". Use for i in *
or similar instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With