简体   繁体   English

使用Regex查找某些文件类型

[英]Using Regex to find certain file types

Having issues trying to copy just jpg , png & JPG files starting with IMG_0000 from one directory to another. 尝试将jpgpngJPG文件从IMG_0000开始从一个目录复制到另一个目录时IMG_0000 I have found the correct expression but I am struggling to make it work. 我找到了正确的表达,但我正在努力使其成功。

Below I have put the correct Regex as well as my code so far. 到目前为止,我已经放置了正确的正则表达式以及我的代码。 The directory I am copying from is /root/memory and the target directory is /root/photoarch . 我从中复制的目录是/root/memory ,目标目录是/root/photoarch Please note that inside /root/memory there are multiple sub-directories and multiple different file types. 请注意,内部/root/memory有多个子目录和多种不同的文件类型。

Regex: 正则表达式:

IMG_[0-9]{4}.[jpg,png,JPG]{3}

Code: 码:

#!bin/bash
mkdir photoarch
find "/root/memory" -regex '.*IMG_[0-9]{4}.[jpg,png,JPG]{3}' -exec cp {} "/root/photoarch"\;

If you are trying to copy files named IMG_<4-digits>.<jpg|JPG|png> , then your regular expression is wrong, as well as its type (by default find uses Emacs RE, not POSIX ERE ). 如果您尝试复制名为IMG_<4-digits>.<jpg|JPG|png> ,那么您的正则表达式及其类型(默认情况下find使用Emacs RE,而不是POSIX ERE )是错误的。

Regarding the regular expression, you'll have to use alternation instead of character range. 关于正则表达式,您将不得不使用替换而不是字符范围。 For example jpg|png will match either jpg or png . 例如jpg|png将匹配jpgpng In contrast, [jpg,png]{3} will match any 3-character sequence of j or p or g or , or n , like jjj , j,p , and pnj . 相比之下, [jpg,png]{3}将匹配的任何3个字符的序列jpg,n ,像jjjj,p ,和pnj Also, you'll have to escape the dot (with \\. ), otherwise it will match any character. 此外,您必须转义点(使用\\. ),否则它将匹配任何字符。

To use POSIX ERE, set -regextype to posix-extended (to list all types accepted, run find -regextype help ). 要使用POSIX ERE,请将-regextype设置为posix-extended (要列出所有接受的类型,请运行find -regextype help )。

For case-insensitive matching, you can use -iregex . 对于不区分大小写的匹配,您可以使用-iregex

find /root/memory -regextype posix-extended -iregex '.*img_[0-9]{4}\.(jpg|png)' -exec cp {} /root/photoarch \;

(The parentheses around jpg|png are necessary because concatenation has higher priority than alternation.) (围绕jpg|png的括号是必要的,因为连接的优先级高于交替。)

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

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