Reputation: 147
I'm trying to fill an array with the files in a folder, but if there are white spaces in their name, they are splitted and the array filled with single words. This is the code with which I try to replace blank spaces with underscore:
array=($(ls)) | sed -r 's/ /_/g'
How to record the ls items into a bash array?
Upvotes: 2
Views: 1066
Reputation: 295403
array=( * ) # populate array with filenames
array=( "${array[@]// /_}" ) # convert spaces to underscores in all array elements
To explain:
array=( $(ls) )
can't be safely used: Unescaped expansion expands globs (if you had a file named *
, it would be replaced with a list of other names) and splits on all whitespace by default (meaning that a file named two words
would become two array entries, the first being two
and the second being words
). Moreover, the behavior of ls
with nonprintable characters is undefined, and its output with files containing literal newlines is necessarily ambiguous."${foo// /_}"
is an expansion of shell variable foo
, with all spaces replaced with underscores. (${foo/ /_}
would replace only the first space with an underscore). For an array, the usual syntax change is applied: ${foo[@]// /_}
. This syntax is comprehensively described in BashFAQ #100 (How do I do string manipulations in bash?).Upvotes: 7