arrays - 数组上的 Bash 子字符串扩展

标签 arrays bash substr expansion

我有一组具有给定后缀的文件。例如,我有一组后缀为 .pdf 的 pdf 文件。 .我想通过子串扩展获取不带后缀的文件名。

对于单个文件我可以使用:

file="test.pdf"
echo ${file:0 -4}

要对所有文件执行此操作,我现在尝试:

files=( $(ls *.pdf) )
ff=( "${files[@]:0: -4}" )
echo ${ff[@]}

我现在收到一个错误提示 substring expression < 0 ..

(我想避免使用 for 循环)

最佳答案

使用parameter expansions像这样删除 .pdf 部分:

shopt -s nullglob
files=( *.pdf )
echo "${files[@]%.pdf}"

shopt -s nullglob 在使用 glob 时总是一个好主意:如果没有匹配项,它将使 glob 扩展为空。

"${files[@]%.pdf}" 将扩展为一个数组,并删除所有尾随 .pdf。你可以,如果你想把它放在另一个数组中:

files_noext=( "${files[@]%.pdf}" )

对于文件名中的有趣符号(空格、换行符等),所有这些都是 100% 安全的,除了名为 -n.pdf 的文件的 echo 部分, -e.pdf-E.pdf... 但是 echo 只是为了演示目的。你的 files=( $(ls *.pdf) ) 真的很糟糕! 永远不要解析 ls 的输出。


回答您的评论:子字符串扩展不适用于数组的每个字段。摘自上面链接的引用手册:

${parameter:offset}

${parameter:offset:length}

If offset evaluates to a number less than zero, the value is used as an offset from the end of the value of parameter. If length evaluates to a number less than zero, and parameter is not @ and not an indexed or associative array, it is interpreted as an offset from the end of the value of parameter rather than a number of characters, and the expansion is the characters between the two offsets. If parameter is @, the result is length positional parameters beginning at offset. If parameter is an indexed array name subscripted by @ or *, the result is the length members of the array beginning with ${parameter[offset]}. A negative offset is taken relative to one greater than the maximum index of the specified array. Substring expansion applied to an associative array produces undefined results.

所以,例如,

$ array=( zero one two three four five six seven eight )
$ echo "${array[@]:3:2}"
three four
$

关于arrays - 数组上的 Bash 子字符串扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20160838/

相关文章:

python - 将 numpy.nd 数组转换为 json

javascript - Parse.com 循环内查询

javascript - 希望在下划线过滤器后返回 ID 列表

java - ArrayDeque 到数组

php - 如何使用 PHP 从字符串中删除最后一个逗号?

php - Opencart PayPal Express 错误 18112

php - 异常的PHP字符串长度以及使用PHP搜索Elasticsearch时

bash - 使用 shell 脚本反转十六进制数

linux - 在启动时启动受限制的 Node.js 应用程序

linux - 如何在 bash 脚本中将数组中的所有值作为参数一个一个地传递?