简体   繁体   中英

Bash regex match

I want to match a line using a regular expression, but can quiet see why it won't work.

To explain my situation: say i have a script like this:

text="/location/whatever/
/some-other-stuff/
/this-is-what-i-need-1/
/this-is-what-i-need-2/
/this-is-what-i-need-3/
/some-other-random-stuff"

#now loop through it:
while read -r line
do
    if [[ "$line" =~ '\/[a-zA-Z\-]*[0-9]+\/' ]]
    then
        #do whatever you like
    fi
done <<< "$text"

I now want to only match lines in the form of "this-is-what-i-need-". My first regex would've been this: \\/[a-zA-Z\\-]*[0-9]+\\/ but it doesn't seem to match any of these lines. I really would like to understand why that is so.

I prefer one liners. You might want to check

echo "$text" | egrep '\/[a-zA-Z\-]*[0-9]+\/' | xargs -i echo "Do something with {}"

You can use any program instead of echo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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