Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract multiple occurrences on the same line using sed/regex

Tags:

regex

sed

I am trying to loop through each line in a file and find and extract letters that start with ${ and end with }. So as the final output I am expecting only SOLDIR and TEMP(from inputfile.sh).

I have tried using the following script but it seems it matches and extracts only the second occurrence of the pattern TEMP. I also tried adding g at the end but it doesn't help. Could anybody please let me know how to match and extract both/multiple occurrences on the same line ?

inputfile.sh:

.  
.  
SOLPORT=\`grep -A 4 '\[LocalDB\]' \${SOLDIR}/solidhac.ini | grep \${TEMP} | awk '{print $2}'\`  
.  
.  

script.sh:

infile='inputfile.sh'  
while read line ; do    
  echo $line | sed 's%.*${\([^}]*\)}.*%\1%g'  
done < "$infile"  
like image 818
user1292603 Avatar asked Mar 26 '12 09:03

user1292603


2 Answers

May I propose a grep solution?

grep -oP '(?<=\${).*?(?=})'

It uses Perl-style lookaround assertions and lazily matches anything between '${' and '}'.

Feeding your line to it, I get

$ echo "SOLPORT=\`grep -A 4 '[LocalDB]' \${SOLDIR}/solidhac.ini | grep \${TEMP} | awk '{print $2}'\`" | grep -oP '(?<=\${).*?(?=})'
SOLDIR
TEMP
like image 150
Lev Levitsky Avatar answered Oct 16 '22 07:10

Lev Levitsky


This might work for you (but maybe only for your specific input line):

sed 's/[^$]*\(${[^}]\+}\)[^$]*/\1\t/g;s/$[^{$]\+//g'
like image 27
Zsolt Botykai Avatar answered Oct 16 '22 07:10

Zsolt Botykai