How to extract part of string in bash using regex

Member

by gilbert , in category: Third Party Scripts , 5 days ago

How to extract part of string in bash using regex

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , 4 days 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.