How to extract part of string in bash using regex

Member

by gilbert , in category: Third Party Scripts , 4 months ago

How to extract part of string in bash using regex

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , 4 months ago

@gilbert 

You can use the grep command with the -o option to extract part of a string in bash using a regular expression. Here is an example:

1
2
3
4
5
string="Hello, world! This is a test string."
pattern='[0-9]+'

result=$(echo $string | grep -o $pattern)
echo $result


In this example, we have a string Hello, world! This is a test string. and we want to extract any numbers present in the string. The regular expression [0-9]+ matches one or more digits. The grep -o command will output only the matched part of the string, which in this case will be any numbers found in the input string.


You can replace the pattern [0-9]+ with any other regular expression that matches the part of the string you want to extract.

Related Threads:

How to extract part of string using regex?
How to extract specific part from a string in mysql?
How to remove part of file name using a regex expression?
How to get the second part of a hyphenated word using regex?
How to extract specific from the url using regex?
How to extract data in paragraph using regex?