如何在 bash 的正则表达式中使用变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47139195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use variables in regular expressions in bash?
提问by Radias Pro
How can I include a variable in my regular expression (grep -o) in bash?
如何在 bash 的正则表达式 (grep -o) 中包含变量?
I just tried it like this, but it didn't worked:
我只是像这样尝试过,但没有奏效:
#!/bin/bash
var=1234
cat test.txt |grep -0 '[0-9]*${var}[0-9]'
回答by Akshay Hegde
Use double quotes, and no need of cat
使用双引号,不需要 cat
var=1234
grep -o "[0-9]*${var}[0-9]" yourfile
variable expands because it is between double quotes (whatever inside single quotes are just characters)
变量扩展,因为它在双引号之间(单引号内的任何内容都只是字符)
See how it works
看看它怎么运作
$ cat test.sh
#!/usr/bin/env bash
set -x
var=1234
echo '[0-9]*${var}[0-9]'
echo "[0-9]*${var}[0-9]"
Output:
输出:
$ bash test.sh
+ var=1234
+ echo '[0-9]*${var}[0-9]'
[0-9]*${var}[0-9]
+ echo '[0-9]*1234[0-9]'
[0-9]*1234[0-9]