Bash 从文件名中提取数字

Bash 从文件名中提取数字,bash,Bash,我正在做一个bash脚本,它可以自动为我运行模拟。为了启动模拟,另一个脚本需要一个输入,该输入应由文件夹的名称指定 因此,如果我有一个文件夹名为No200,那么我想提取数字200。到目前为止,我得到的是 PedsDirs=`find . -type d -maxdepth 1` for dir in $PedsDirs do if [ $dir != "." ]; then NoOfPeds = "Number appearing in the name

我正在做一个bash脚本,它可以自动为我运行模拟。为了启动模拟,另一个脚本需要一个输入,该输入应由文件夹的名称指定

因此,如果我有一个文件夹名为No200,那么我想提取数字200。到目前为止,我得到的是

PedsDirs=`find . -type d -maxdepth 1`
for dir in $PedsDirs
do
        if [ $dir != "." ]; then
            NoOfPeds = "Number appearing in the name dir" 
        fi
done
通常,要删除前缀,请使用
${variable name#prefix}
;要删除后缀:
${variable name%suffix}


奖励提示:避免使用
find
。它会带来很多问题,尤其是当文件/目录包含空格时。改用bash内置glob功能:

for dir in No*/           # Loops over all directories starting with 'No'.
do
    dir="${dir%/}"        # Removes the trailing slash from the directory name.
    NoOfPeds="${dir#No}"  # Removes the 'No' prefix.
done

此外,尽量在变量名周围使用引号,以避免意外扩展(即使用
“$dir”
,而不仅仅是
$dir
)。

要小心,因为在bash中必须将
=
与变量名连接起来。要仅获取数字,您可以执行以下操作:

NoOfPeds=`echo $dir | tr -d -c 0-9`
(也就是说,删除任何不是数字的字符)。然后,所有数字都将出现在
NoOfPeds

NoOfPeds=`echo $dir | tr -d -c 0-9`