LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   bash replace all matches of regex substring in string (https://www.linuxquestions.org/questions/linux-general-1/bash-replace-all-matches-of-regex-substring-in-string-435024/)

nickleus 04-14-2006 03:59 AM

bash replace all matches of regex substring in string
 
Hi yall, i've been searching and testing for a while, but can't find a way to replace all instances of a regex substring in a string, just with bash. I found this:
Code:

${parameter//pattern/string}
given this:
Code:

temp=<year>2006</year> <month>04</month>
when i run this:
Code:

echo ${temp//[^digit]/}
it prints out:
tt

I want to remove all characters except for numbers. Is this possible?

acid_kewpie 04-14-2006 04:07 AM

Check this:
Code:

chris@kermit ~ $ experiment=supercall2345i7fragilisticexpi6a7lad22o3c5ious
chris@kermit ~ $ echo ${experiment//[0-9]/}
supercallifragilisticexpialadocious
chris@kermit ~ $ echo ${experiment//[^0-9]/}
23457672235
chris@kermit ~ $


nickleus 04-14-2006 04:08 AM

crap, i can't believe i didn't try 0-9. thanks chris!

schworak 04-30-2011 11:08 AM

I know this is a very old post but I stumbled upon it and wanted to offer an alternative to anyone else that stumbles on it.


#!/bin/bash
tmp="<year>2008</year> <month>08</month>"
echo ${tmp//[^[:digit:]]}



When using the named character groups they need to be wrapped in [: :]. The original post just used the word "digit" so any character that didn't match d, i, g or t was removed. "t" was the only letter that matched in the original string (one in each "month" tag) so that is why "tt" was returned.


All times are GMT -5. The time now is 10:33 PM.