Shell regex to end of line

若如初见. 提交于 2021-01-27 14:20:54

问题


I have a file like this little example:

# ...
# mode=dev
# ...

Somewhere in this file there is a "variable" within a comment. And i would like to get the value with regex in a Shell script.

My code so far:

#!/bin/bash
conf=$(<"/etc/test.conf") # Get the file content
regex='mode=(.*)$' # Set a regex
if [[ $conf =~ $regex ]]; then # Search for the regex in the file
    # We found it, so ...
    echo "${BASH_REMATCH[1]}" # ... here is the value
fi  

My big problem is, that it will not find the value :(
I tried a lot of different regex expressions and tested them with https://regex101.com/ , but it seems, that the Shell regex interprator is different from pcre and python.

My best solution was to find the mode= and everything after it. So is there a way to get only the value? The start is easy ... find mode=. But how do I say the shell regex to get everything behind mode= until the next linebreak? and not beyond this linebreak?
Something with \n (unix linebreak) and $ (end of string) did not work for me :(

Thanks for the help,
greetings


回答1:


You can use this regex to get your match:

conf=$(<"/etc/test.conf")
regex=$'mode=([^\n]*)'
[[ $conf =~ $regex ]] && echo "${BASH_REMATCH[1]}"

Output:

dev

Regex $'mode=([^\n]*)' will match literal text mode= followed by 0 or more of any character that is not \n.



来源:https://stackoverflow.com/questions/32952541/shell-regex-to-end-of-line

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