regex - 如何在 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]}'"
任何人都可以帮助我非常感谢
解决方案
这是你想要做的吗?
$ 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:]_]
推荐阅读
- python-3.x - Azure Speech to Text 麦克风不会停止连续录音
- arrays - 数组和指针的语法混淆
- flutter - 如何在没有firebase和一个信号的情况下从后端推送通知?
- node.js - GET 请求始终默认为 /(?:)/i - 我怎样才能使其“未定义”?
- codeigniter - Codeigniter 4 使用 save() 更新到数据库
- python-3.x - 如何以不寻常的日期\时间格式阅读
- python-3.x - 蝗虫,on_start 方法不适用于任务
- python - 如何按升序/降序对 Python 中 tweepy 返回的解析不佳的 JSON 数据进行排序?
- node.js - 有没有办法给在 WLAN 中运行的网站“提供 url”?
- python - 在没有 Web 服务器的情况下从 localhost 获取文件