Cor*_*ein 12 sed regular-expression
在使用 时sed
,我经常创建相当复杂和错综复杂的正则表达式,我需要在一个文件中匹配两次。有没有办法让我保存这个正则表达式并只引用它两次?
也许看起来像这样的东西?
sed ' complicated_regex=/^(([a-f0-9]{32})+([a-zA-Z0-9=]{{$i}})?)+$/
s/complicated_regex:complicated_regex/simple-output/
' my_file
Run Code Online (Sandbox Code Playgroud)
更新:一个答案提出了使用 bash 变量的解决方案。这不起作用。给定一个test.txt
.
#test.txt
foo bar
bar foo
Run Code Online (Sandbox Code Playgroud)
还有剧本
#!/bin/bash
VALUE='foo \([a-z]\+\)'
sed 's/"${VALUE}"/foo happy \1/' test.txt
Run Code Online (Sandbox Code Playgroud)
这应该产生输出
foo happy bar
bar foo
Run Code Online (Sandbox Code Playgroud)
但相反,我得到了错误
sed: -e expression #1, char 24: invalid reference \1 on `s' command's RHS
Run Code Online (Sandbox Code Playgroud)
您可以使用 shell 变量:
complicated_regex='(([a-f0-9]{32})+([a-zA-Z0-9=]{{$i}})?)+'
sed s/^"$complicated_regex":"$complicated_regex"\$/'simple-output'/ my_file
Run Code Online (Sandbox Code Playgroud)
我不确定你的意思$i
,但你可能需要把它放在单引号之外:
complicated_regex='(([a-f0-9]{32})+([a-zA-Z0-9=]{{'"$i"'}})?)+'
Run Code Online (Sandbox Code Playgroud)