Regex 用sed失败解析shebang
我有一个像Regex 用sed失败解析shebang,regex,linux,bash,sed,Regex,Linux,Bash,Sed,我有一个像#这样的字符串/bin/bash——args等等,我想从中提取“bash” 它给了我一个错误“bash:syntax error”靠近意外标记“(”) 我用-r启用了扩展正则表达式,不是吗?发生了什么事?您应该引用您的sed命令: echo "$str" | sed -r "s/#\!.*?/(.*?)\>/\1/g" 在bash中,如果paren不在字符串文本中,则具有特殊含义。 此外,您的sed命令将为sed:-e expression#1,char 18:unknown选
#这样的字符串/bin/bash——args等等,我想从中提取“bash”
它给了我一个错误“bash:syntax error”靠近意外标记“(”)
我用-r
启用了扩展正则表达式,不是吗?发生了什么事?您应该引用您的sed命令:
echo "$str" | sed -r "s/#\!.*?/(.*?)\>/\1/g"
在bash中,如果paren不在字符串文本中,则具有特殊含义。
此外,您的sed命令将为sed:-e expression#1,char 18:unknown选项向's'
抛出一个错误,因为您的模式中有一个unscaped/
。似乎字符串赋值错误,并且由于输入包含正向斜杠,因此也使用了不同的sed分隔符
$ str='#!/bin/bash --args blah blah'
$ sed -r 's~#![^ ]*/([^ ]*)\b.*~\1~g' <<< $str
bash
$str='#!/bin/bash--args等等
$sed-r的s~#![^]*/([^]*)\b.*\1~g'使用纯BASH内置:
str='#!/bin/bash --args blah blah'
[[ "$str" =~ \#\!/[^/]+/([^/ ]+) ]] && echo "${BASH_REMATCH[1]}"
bash
纯POSIX,无Bashism,适用于任何Bourne Shell:
$ str='#!/bin/bash --args blah blah'
$ shebang=${str%% *} # Remove space and all that follows
$ shell=${shebang##*/} # Remove up to and including /
$ echo $shell
bash
阅读shell手册中的“参数扩展”一节,了解更多关于内置字符串处理功能的信息。请注意,与使用shell内置功能相比,像sed
这样的外部程序在CPU周期方面非常昂贵。。您也可以使用PCRE:
echo '#!/bin/bash --args blah blah' | grep -Po "(?<=/)[a-z]+(?= )"
echo'#!/bin/bash--args blah blah'| grep-Po“(?可能是真的,但现在它给了我错误”sed:-e expression#1,char 18:unknown option to`s'@MightyPork-Correct。这是因为您的搜索模式包含一个未转义的/
。您可以转义它或使用另一个分隔符。
echo '#!/bin/bash --args blah blah' | grep -Po "(?<=/)[a-z]+(?= )"