Bash string matching
开发者_高级运维I need a single line bash command that takes a piped input and returns true or false depending if it match a string or not..
This seems to work for the true or false part:
test `expr match "Release:11.04" "Release:11.04"` = 13 && echo true || echo false
But I cannot get it to work properly with the other command's output..
What I need would be something like this:
test `expr match "`lsb_release -r`" "Release:11.04"` = 13 && echo true || echo false
So I tried with xargs, but I can't get it to work:
lsb_release -r | xargs -I {} test `expr {} "Release: 11.04"` = 13 && echo True || echo False
Also, if any of you happens to know a shorter way to achieve this, it would be greatly welcome.
You could use the $(cmd) syntax.
test $(expr match "$(lsb_release -r)" "Release:11.04") = 13 && echo true || echo false
Though on my system there is a tab in the output of lsb_release after ':', so you may want to doublecheck your checks.
And actually after fiddling a bit, I think this would be a nicer way with bash (tested on Debian system):
[[ "$(lsb_release -r)" =~ $'Release:\t6.0.2' ]] && echo true || echo false
Why not this way:
[ `lsb_release -r | awk '{print $2}'` = "11.04" ] && echo true || echo false
BTW, if you need to use nested ``
you can escape inner one with \
like that:
test `expr match "\`lsb_release -r\`" "Release:11.04"`
But it looks ugly. Using $() is more readable, but bit less portable.
This would be another simpler approach -
lsb_release -r | grep -q "11.04" && echo true || echo false
Basically, this greps the output of lsb_release -r
for 11.04. -q
in grep will return exit status zero if a match is found, which will echo true
. false
otherwise.
精彩评论