我在shell中,我有这个字符串: 12 BBQ ,45 rofl, 89 lol
使用正则表达式:\d+ (?=rofl)我想要45的结果.
使用正则表达式从字符串中提取数据是否正确?我所做的最好的是突出一些在线正则表达式编辑器的价值.大多数情况下它会从我的字符串中删除值.
我正在调查expr,但我得到的只是语法错误.
如何设法在shell脚本中提取45?
Mat*_*hen 51
您可以使用GNU grep的perl模式执行此操作:
echo "12 BBQ ,45 rofl, 89 lol"|grep -P '\d+ (?=rofl)' -o
Run Code Online (Sandbox Code Playgroud)
-P表示Perl风格,-o仅表示匹配.
Ste*_*eet 13
是的正则表达式当然可以用来提取字符串的一部分.不幸的是,*nix和不同工具的不同风格使用略有不同的Regex变体.
这个sed命令应该适用于大多数风格(在OS/X和Redhat上测试)
echo '12 BBQ ,45 rofl, 89 lol' | sed 's/^.*,\([0-9][0-9]*\).*$/\1/g'
Run Code Online (Sandbox Code Playgroud)
看来你在问多种事情.回答他们:
您可以通过捕获括号中的数字来提取数字:
.*(\d+) rofl.*
Run Code Online (Sandbox Code Playgroud)
并$1用来获取字符串(.*用于"在同一行之前和之后的其余部分)
以sed为例,我们的想法是用一个匹配的数字替换文件中的所有字符串:
sed -e 's/.*(\d+) rofl.*/$1/g' inputFileName > outputFileName
Run Code Online (Sandbox Code Playgroud)
要么:
echo "12 BBQ ,45 rofl, 89 lol" | sed -e 's/.*(\d+) rofl.*/$1/g'
Run Code Online (Sandbox Code Playgroud)
rg --only-matching --replace '$1' '(\d+) rofl'
Run Code Online (Sandbox Code Playgroud)
--only-matching或-o仅输出匹配的部分而不是整行。--replace '$1'或-r用第一个捕获组替换输出。