String text = "This is a very tiny test!!!"
Pattern p = "this is a (.*) test.*"
Output o = "very tiny" (after search and replace)
我想用括号()内的内容替换模式,其中索引为$1。在 Linux 上,什么命令可以执行此操作以及如何执行此操作?
我必须在命令行执行此操作,因为我的文件有几 GB,无法在编辑器中完成。
最佳答案
使用 GNU sed:
s='This is a very tiny test!!!'
sed -En 's/this is a (.*) test.*/\1/ip' <<< $s
输出:
very tiny
i
- 正则表达式匹配的 I
修饰符是一个 GNU 扩展,它使 sed 以不区分大小写的方式匹配 regexp。
备选 perl 方法:
perl -nle 'print $1 if /this is a (.*) test.*/i' <<< $s
关于linux - 搜索并替换为反向引用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44012125/