简体   繁体   English

某些长度的匹配文件仅包含数字?

[英]Matching files of certain length that only contain digits?

I've been trying to match all file names in a directory that are 6 characters long and only contain digits. 我一直在尝试匹配目录中所有文件名,这些文件名长6个字符,并且仅包含数字。 I've been banging my head trying to get it to work but with no luck. 我一直在想办法使其正常工作,但是没有运气。 This is what I have: 这就是我所拥有的:

for f in "$path"*
do
        if echo "$f" | tail -c 7 | grep "^[[:digit:]][:digit:]]*$"; then
                echo "$f is good"
        else
                echo "$f" | tail -c 7
        fi
done

Every time I run the script the else gets ran and I just get the last 6 characters from each file in the directory. 每次我运行脚本时,其他脚本都会运行,而我只会从目录中的每个文件中获取最后6个字符。 I don't want to have to cd into the directory to check the files so I thought taking the last 6 and checking would be a good idea (maybe not). 我不想进入目录来检查文件,所以我认为最后6个检查是个好主意(也许不是)。 I want to eventually redirect all files in $path that are 6 characters long and all digits. 我最终希望重定向$ path中所有长度为6个字符和所有数字的所有文件。 I just cant figure out how to match this. 我只是不知道如何匹配。 Thank you! 谢谢!

here is a one liner to just list the filenames: 这是一个只列出文件名的衬里:

for f in "$path"[0-9][0-9][0-9][0-9][0-9][0-9];do echo ${f##*/};done

if you want the full path just omit the ##*/ 如果您想要完整的路径,只需省略##*/

ls [0-9][0-9][0-9][0-9][0-9][0-9]

Or, if you simply want to edit your script: 或者,如果您只想编辑脚本:

for f in "$path"*
do
    if echo "$f" | tail -c 7 | grep "^[[:digit:]][[:digit:]][[:digit:]][[:digit:]][[:digit:]][[:digit:]]$"; then
            echo "$f is good"
    else
            echo "$f" | tail -c 7
    fi
done

Or, just use the regex pattern: 或者,只需使用正则表达式模式:

'^[[:digit:]]{6}$'

Use basename to get the filename part of a pathname, and test that: 使用basename获取路径名的文件名部分,并进行以下测试:

for f in "$path"*
do
    base=$(basename "$f")
    case "$base" in
        [0-9][0-9][0-9][0-9][0-9][0-9])
            echo "$f is good" ;;
        *) echo "$base" ;;
    esac
done

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

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