我有一组具有给定后缀的文件。例如,我有一组后缀为 .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 ofparameter
. Iflength
evaluates to a number less than zero, andparameter
is not@
and not an indexed or associative array, it is interpreted as an offset from the end of the value ofparameter
rather than a number of characters, and the expansion is the characters between the two offsets. Ifparameter
is@
, the result islength
positional parameters beginning at offset. Ifparameter
is an indexed array name subscripted by@
or*
, the result is thelength
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/