简体   繁体   English

如何在bash数组的所有条目中用下划线替换空格

[英]How to substitute spaces with underscores in all entries in a bash array

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? 如何将ls项记录到bash数组中?

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 ). 无法安全使用array=( $(ls) ) :非转义扩展扩展globs(如果你有一个名为*的文件,它将被其他名称列表替换)并默认拆分所有空格(意味着名为two words文件将成为两个数组条目,第一个是two ,第二个是words Moreover, the behavior of ls with nonprintable characters is undefined, and its output with files containing literal newlines is necessarily ambiguous. 此外,具有不可打印字符的ls的行为是未定义的,并且其包含文字换行符的文件的输出必然是不明确的。
  • "${foo// /_}" is an expansion of shell variable foo , with all spaces replaced with underscores. "${foo// /_}"是shell变量foo的扩展,所有空格都用下划线替换。 ( ${foo/ /_} would replace only the first space with an underscore). ${foo/ /_}只会用下划线替换第一个空格)。 For an array, the usual syntax change is applied: ${foo[@]// /_} . 对于数组,应用通常的语法更改: ${foo[@]// /_} This syntax is comprehensively described in BashFAQ #100 (How do I do string manipulations in bash?) . BashFAQ#100(如何在bash中进行字符串操作?)中全面描述了这种语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM