首页 > 解决方案 > 如何在 shell 文件(.sh)中使用正则表达式来捕获“\”和换行符(换行符)?

问题描述

我正在尝试在 shell 文件 (.sh) 中捕获 '\' 和换行符。我在网站上试过:https ://regexr.com/它有效。但似乎方式与shell文件中的方式不一样。

这是目标,我想得到这三个匹配组

 some dummy code in front of
blablabla
 CE3( Match_Group_1, \(some space may right after this backslash)
      Match_Group_2, \(some space may right after this backslash)
      Match_Group_3,    \(some space may right after this backslash)
      abcabc1234,   \(some space may right after this backslash)
    abcd12345      )

blablabla
     blablabla

我在https://regexr.com/中的正则表达式:'\s*' 可以捕获空格、制表符和换行符。通过 (\w+) 获取这些匹配组

 \s*\(\s*(\w+)\s*,\s*\\\s*(\w+)\s*,\s*\\\s*(\w+)

我在 shell 文件中的正则表达式进行匹配然后打印:它未能获得这三个匹配组

 awk_cmd="awk 'match(\$0, /(${i})\\s*\(\\s*(\\w+)\\s*,\\s*\\\\s*(\\w+)\\s*,\\s*\\\\s*(\\w+)/, g) {print FILENAME \",\" NR \",\" g[1] \",\" g[3] \",\" g[4]}'"

任何人都可以帮助我非常感谢

标签: regexbashshellawk

解决方案


这是你想要做的吗?

$ awk_cmd() {
    awk -v RS='^$' -v OFS='","' '
        match($0,/\s*\(\s*(\w+)\s*,\s*\\\s*(\w+)\s*,\s*\\\s*(\w+)/,g) {
            print "\"" FILENAME, NR, g[1], g[2], g[3] "\""
        }
    ' "$@"
}

$ awk_cmd file
"file","1","Match_Group_1","Match_Group_2","Match_Group_3"

$ cat file | awk_cmd
"-","1","Match_Group_1","Match_Group_2","Match_Group_3"

由于您的正则表达式必须跨越多行,因此不清楚您期望 NR 具有什么值。在上面,我将整个输入文件视为单个记录,因此 NR 将始终为 1。如果您尝试打印与正则表达式匹配的字符串开始的行号,则为:

$ awk_cmd() {
    awk -v RS='^$' -v OFS='","' '
        match($0,/(.*)\s*\(\s*(\w+)\s*,\s*\\\s*(\w+)\s*,\s*\\\s*(\w+)/,g) {
            nr = gsub(/\n/,"&",g[1]) + 1
            print "\"" FILENAME, nr, g[2], g[3], g[4] "\""
        }
    ' "$@"
}

$ awk_cmd file
"file","3","Match_Group_1","Match_Group_2","Match_Group_3"

以上使用 GNU awk 表示多字符 RS 和第三个参数 match() 和以及\s\w的简写。[[:space:]][[:alnum:]_]


推荐阅读