Input:
hello world "22" bye world
I need a regex that will work in bash that can get me the numbers between the quotes. The regex should match 22.
Thanks!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There are not really regexes in bash itself. There are however some programs that can use regexes, amongst them
grepandsed.grep’s main functionality is to filter lines that match a given regex, ie you give it some data to stdin or a file and it prints the lines that match the regex.
sed does transform data. It doesn’t just return the matching lines, you can tell it what to return with the
s/regex/replacement/command. The output part can contain references to groups (\xwhere x is the number of the group), if you specify the-roption.So what we need is
sed. Your input contains some stuff (^.*), a", some digits ([0-9]+), a", and some stuff (.*$). We later need to reference the digits, so we need to make the digits a group. So our complete matching regex is:^.*"([0-9]+)".*$. We want to replace that with only the digits, so the replacement part is just\1.Building the complete sed command is left as an exercise to you
:-)(Note that sed does not transform lines that don’t match. If your input is only the line you provided above, that’s fine. If there are other lines you’d like to silently skip, you need to specify the option
-n(no automatic printing) and add anto the end of the sed expression, which instructs it to print the line. That way it only prints the matching line(s).)