[英]Regex is not matching for shell script: sed 's| *MOVE *\([^ ]*\) .*|\1|
I am facing pretty strange problem, below is shell script with sed command: 我面临一个非常奇怪的问题,下面是带有sed命令的shell脚本:
rec="001 MOVE 'N' TO abcdefgef"
vname=`sed 's| *MOVE *\([^ ]*\) .*|\1|' <<<$rec`
echo "vname=$vname"
output: vname=001'N' 输出:vname = 001'N'
I am expecting it to be only as 'N' not 001'N'. 我希望它只能是'N'而不是001'N'。 Could someone please explain why 001 is coming in output?
有人可以解释为什么输出001吗? if regular exp is not matching i should be gettign complete string as ouput.
如果正则表达式不匹配,我应该使用完整的字符串作为输出。 And if 001 is matching how it can miss MOVE word?
如果001匹配,怎么会错过MOVE单词?
$ rec="001 MOVE 'N' TO abcdefgef"
$ echo "$rec" | sed 's| *MOVE *\([^ ]*\) .*|\1|'
001'N'
$ echo "$rec" | sed 's|.* *MOVE *\([^ ]*\)|\1|'
'N' TO abcdefgef
$ echo "$rec" | sed 's|.* *MOVE *\([^ ]*\) .*|\1|'
'N'
$ echo "MOVE 'N' TO" | sed 's|.* *MOVE *\([^ ]*\) .*|\1|'
'N'
Just like you added .*
to match rest of line after capturing your required string, you need to add .*
to match string before MOVE...
就像您在捕获所需的字符串后添加
.*
以匹配其余行一样,您需要在MOVE...
之前添加.*
以匹配字符串MOVE...
Also, you probably want to match the space after MOVE
instead of making it optional 另外,您可能想在
MOVE
之后匹配空格,而不是将其设置为可选
$ echo "MOVED TO" | sed 's|.* *MOVE *\([^ ]*\) .*|\1|'
D
$ echo "MOVED TO" | sed 's|.* *MOVE \([^ ]*\) .*|\1|'
MOVED TO
You can do regex matching in bash: 您可以在bash中进行正则表达式匹配:
rec="001 MOVE 'N' TO abcdefgef"
regex='MOVE *([^ ]+)'
[[ $rec =~ $regex ]] && declare -p BASH_REMATCH
declare -ar BASH_REMATCH='([0]="MOVE '\''N'\''" [1]="'\''N'\''")'
"BASH_REMATCH" is an array that, if the match succeeded, will be populated with the matched text (in array index 0) and the captured parts of the regex (in subsequent indices) “ BASH_REMATCH”是一个数组 ,如果匹配成功,将使用匹配的文本(在数组索引0中)和正则表达式的捕获部分(在后续索引中)填充
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.