Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unix: how to tell if a string matches a regex

Trying out fish shell, so I'm translating my bash functions. The problem is that in one case, I'm using bash regexes to check if a string matches a regex. I can't figure out how to translate this into fish.

Here is my example.

if [[ "$arg" =~ ^[0-9]+$ ]]
...
  • I looked into sed, but I don't see a way to get it to set its exit status based on whether the regex matches.
  • I looked into delegating to Ruby, but again, getting the exit status set based on the match requires making this really ugly (see below).
  • I looked into delegating back to bash, but despite trying maybe three or four ways, never got that to match.

So, is there a way in *nix to check if a string matches a regex, so I can drop it into a conditional?


Here is what I have that currently works, but which I am unhappy with:

# kill jobs by job number, or range of job numbers
# example: k 1 2 5
# example: k 1..5
# example: k 1..5 7 10..15
# example: k 1-5 7 10-15
function k
  for arg in $argv
    if ruby -e "exit ('$arg' =~ /^[0-9]+\$/ ? 0 : 1)"
      kill -9 %$arg
    else
      set _start (echo "$arg" | sed 's/[^0-9].*$//')
      set _end   (echo "$arg" | sed 's/^[0-9]*[^0-9]*//')

      for n in (seq $_start $_end)
        kill -9 %"$n"
      end
    end
  end
end
like image 704
Joshua Cheek Avatar asked May 19 '13 04:05

Joshua Cheek


People also ask

How do I check if a string matches in regex Bash?

You can use the test construct, [[ ]] , along with the regular expression match operator, =~ , to check if a string matches a regex pattern (documentation). where commands after && are executed if the test is successful, and commands after || are executed if the test is unsuccessful.

Does grep support regex?

Grep Regular ExpressionGNU grep supports three regular expression syntaxes, Basic, Extended, and Perl-compatible. In its simplest form, when no regular expression type is given, grep interpret search patterns as basic regular expressions.

Can I use sed with regex?

Regular expressions are used by several different Unix commands, including ed, sed, awk, grep, and to a more limited extent, vi.


2 Answers

I would suggest to use the built-in string match subcommand

if string match -r -q  '^[0-9]+$' $arg
  echo "number!"
else
  echo "not a number"
end
like image 121
oschrenk Avatar answered Oct 18 '22 16:10

oschrenk


The standard way is to use grep:

if echo "$arg" | grep -q -E '^[0-9]+$'
  kill -9 %$arg
like image 35
choroba Avatar answered Oct 18 '22 15:10

choroba