正则表达式不匹配文件路径中的名称

时间:2017-07-28 10:22:44

标签: regex bash

我有一个包含ipa文件的文件夹。我需要在文件名中包含appstoreenterprise来识别它们。

mles:drive-ios-swift mles$ ls build
com.project.drive-appstore.ipa                                   
com.project.test.swift.dev-enterprise.ipa
com.project.drive_v2.6.0._20170728_1156.ipa                      

我试过了:

#!/bin/bash -veE

fileNameRegex="**appstore**"

for appFile in build-test/*{.ipa,.apk}; do
if [[ $appFile =~ $fileNameRegex ]]; then
    echo "$appFile Matches"
else
    echo "$appFile Does not match"
fi
done

然而没有匹配:

mles:drive-ios-swift mles$ ./test.sh 
build-test/com.project.drive-appstore.ipa Does not match
build-test/com.project.drive_v2.6.0._20170728_1156.ipa Does not match
build-test/com.project.test.swift.dev-enterprise.ipa Does not match
build-test/*.apk Does not match

正确的脚本如何匹配build-test/com.project.drive-appstore.ipa

2 个答案:

答案 0 :(得分:1)

您在 glob 字符串匹配与正则表达式匹配之间感到困惑。对于像*这样的贪婪的全局匹配,您只需将测试运算符与==一起使用,

#!/usr/bin/env bash

fileNameGlob='*appstore*'
#            ^^^^^^^^^^^^ Single quote the regex string   

for appFile in build-test/*{.ipa,.apk}; do        
    # To skip non-existent files
    [[ -e $appFile ]] || continue

    if [[ $appFile == *${fileNameGlob}* ]]; then
        echo "$appFile Matches"
    else
        echo "$appFile Does not match"
    fi
done

产生结果

build-test/com.project.drive_v2.6.0._20170728_1156.ipa Does not match
build-test/com.project.drive-appstore.ipa Matches
build-test/com.project.test.swift.dev-enterprise.ipa Does not match

(或)正则表达式使用贪婪匹配.*作为

fileNameRegex='.*appstore.*'
if [[ $appFile =~ ${fileNameRegex} ]]; then
    # rest of the code

那就是说你的原始要求与文件名中的enterpriseappstore字符串匹配,请使用bash中的扩展的全局匹配

使用glob:

shopt -s nullglob
shopt -s extglob
fileExtGlob='*+(enterprise|appstore)*'

if [[ $appFile == ${fileExtGlob} ]]; then
    # rest of the code

和正则表达式,

fileNameRegex2='enterprise|appstore'
if [[ $appFile =~ ${fileNameRegex2} ]]; then
    # rest of the code

答案 1 :(得分:1)

您可以使用以下正则表达式在文件名中匹配appstore和enterprise:

for i in build-test/*; do if [[ $i =~ appstore|enterprise ]]; then echo $i; fi; done