- I would like to be able to put the file names in a directory into an
- array in bash. I have a script that works as long as there are no
- spaces in the file name. When there is a space in a name, each part of
- the file name ends up in a separate element.
- The script:
- #!/bin/bash
- # List files, ignoring directories.
- ls -1pQ | grep -v '/'
- echo
- # Put the file names in an array.
- declare -a fn
- fn=( `ls -1pQ | grep -v '/'` )
- # Print the number of elements in the array.
- echo 'count='${#fn[*]}
- echo
- # Print all array elements, one per line.
- n=0
- for name in ${fn[@]}
- do
- let "n=$n+1"
- echo $n':' $name
- done
- exit
- The terminal output:
- "new file.txt"
- "test"
- count=3
- 1: "new
- 2: file.txt"
- 3: "test"
- I would like to be able to do it without creating a temporary disk
- file. It is possible to make it work by using sed to replace each
- space with some other character, then reversing the substitution
- later. However, that seems kind of heavy-handed.
- Any other thoughts on how to make this work?
SHARE
TWEET
Untitled
a guest
Dec 20th, 2012
36
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
RAW Paste Data
