Shell脚本 - 循环文件名并提取文件名中的数字

时间:2021-07-03 17:29:16

Using a linux shell script, I am trying to loop through all of the file names in a directory and extract the numbers out of the file name before I process the file.

使用linux shell脚本,我试图遍历目录中的所有文件名,并在处理文件之前从文件名中提取数字。

Something like this:

像这样的东西:

for files in `ls *.gz`
do
        echo "Looking at...  $files"
        gunzip $files
        echo "$files" | awk '/[0-9]/' ' {print $1}'
        echo "$files is  unzipped"
done

Thank you for any help with this.

感谢您对此的任何帮助。

1 个解决方案

#1


2  

You can substitute all non-numbers in the file name.

您可以替换文件名中的所有非数字。

echo "${files//[!0-9]/}"

This will obviously produce concatenated numbers if a file name contains multiple runs of digits. For example, 12a34.gz gets turned into 1234.

如果文件名包含多个数字运行,这显然会产生连接数字。例如,12a34.gz变为1234。

This substitution mechanism is a Bash-only feature, and not supported by plain sh.

此替换机制是仅限Bash的功能,并且不受plain sh支持。

#1


2  

You can substitute all non-numbers in the file name.

您可以替换文件名中的所有非数字。

echo "${files//[!0-9]/}"

This will obviously produce concatenated numbers if a file name contains multiple runs of digits. For example, 12a34.gz gets turned into 1234.

如果文件名包含多个数字运行,这显然会产生连接数字。例如,12a34.gz变为1234。

This substitution mechanism is a Bash-only feature, and not supported by plain sh.

此替换机制是仅限Bash的功能,并且不受plain sh支持。