Linux file names & file globbing

别来无恙 提交于 2019-12-10 15:58:57

问题


I have a list of files named:

file000
file001
file002
file003
...
file1100

How can I match all files that have a number greater than 800 but less than 1000 ? I am using linux bash

Thank you


Edit

Actually, my files are named like:
ab869.enc
cp936.enc
g122345.enc
x2022.enc
abc8859-14.enc
aax5601.enc
cp936-1.enc

so the first solution dont match the correct files :(

How can I match files that have number between 800-999 ?


回答1:


*[89][0-9][0-9].enc

That uses Bash's "pathname expansion" feature (aka "globbing") to match all files ending with a number between 800 and 999 followed by ".enc". (This is not a regular expression).

For example, using the above expression you can do this in your script:

mv *[89][0-9][0-9].enc path/to/destination/

If you need it to also match a file named like "cp850-1.enc", then you would need to change the expression to:

*[89][0-9][0-9]*.enc



回答2:


In shell, try this:

ls file{801..999}

This will list the files starting with file801 and ending with file999.

For explanation, see the manual:

  • http://www.gnu.org/software/bash/manual/bashref.html#Brace-Expansion



回答3:


This provides an interesting expansion but can not be tested without the original files in a directory.

echo [a-z,A-Z]*{801..999}[a-z,A-Z]*.enc

There should be an asterisk after both sets of brackets.




回答4:


Take your pick.

ls | awk -F'[^0-9]*' '800<$2&&$2<1000'  # assuming no filenames start with number

perl -le'/(\d+)/&&800<$1&&$1<1000&&print for<*>'



回答5:


This is close to what you want:

$ ls *{800..999}{,-*}.enc

ab869.enc  abc8859-14.enc  cp936-1.enc  cp936.enc

The trouble is that you're picking up abc8859-14.enc, which you don't want. In this case, egrep will be your friend:

$ ls *{800..999}{,-*}.enc | egrep '[^0-9][0-9]{3}(|-.*)\.enc'

If you want to move or copy files, you'll probably want to wrap this expression in a for loop (in certain circumstances, you might be able to use xargs rather than a for loop).

 for file in $(ls *{800..999}{,-*}.enc | egrep '[^0-9][0-9]{3}(|-.*)\.enc')
 do
      # copy abc859-14.enc to abc859-14.bak
      basefile=$(basename $file .enc)
      cp $file "$basefile.bak"
 done


来源:https://stackoverflow.com/questions/10065164/linux-file-names-file-globbing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!