LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   regex in shell scripts (https://www.linuxquestions.org/questions/linux-newbie-8/regex-in-shell-scripts-771387/)

vinaytp 11-25-2009 01:21 AM

regex in shell scripts
 
Hi all..

Code:

[vinay@TEG test]$ echo 'text[2*?!]' | sed 's/text*[2-4]*/vinay/'
vinay[2*?!]

Code:

[vinay@TEG test]$ echo 'text[2*?!]' | sed 's/text*[2-4]/vinay/'
text[2*?!]

In second case text* should match text in text[2*?!] and the output should be vinay[2*?!] right ?

Disillusionist 11-25-2009 01:33 AM

wrong, although I guess you knew that already.

Quote:

sed 's/text*[2-4]/vinay/'
This would match:

tex2
tex3
tex4
text2
text3
text4
textt2
textt3
textt4

Basically, match tex then any number of the character t (including zero) followed by a number between 2 and 4

Disillusionist 11-25-2009 01:48 AM

Try:

Code:

echo 'text[2*?!]'|sed 's/\(text\)\(\[[2-4]\)/vinay\2/'
\(text\) searces for an exact match for text
\(\[[2-4]\) searches for a litteral [ character followed by a number between 2 and 4

Therefore \1 refers to text (but we are not using this part.

\2 refers (in this instance) to [2

We replace the search with vinay followed by the second reference [2 the rest of the string is kept as it wasn't part of the search.

HTH,

Dis

vinaytp 11-25-2009 03:45 AM

Hi Disillusionist

Quote:

Originally Posted by Disillusionist (Post 3768833)
Try:

Code:

echo 'text[2*?!]'|sed 's/\(text\)\(\[[2-4]\)/vinay\2/'

is giving output as
vinay[2*?!]

Actually output should be
vinay[2

Also you are escaping [ with \ to match [, I hope its not necessary..why its matching whole [2*?!] ??

Till now i have read lot of material on regex..still struggling to find answers..

Tinkster 11-25-2009 03:58 AM

Quote:

Originally Posted by vinaytp (Post 3768960)
Hi Disillusionist



is giving output as
vinay[2*?!]

Actually output should be
vinay[2

Why do you think so? Please explain.

Quote:

Originally Posted by vinaytp (Post 3768960)
Also you are escaping [ with \ to match [, I hope its not necessary..why its matching whole [2*?!] ??

It isn't. It's only replacing the matched text (which happens to include
[2-4) and putting it back in the replacement string with \2 ... '*?!]' wasn't
matched and won't be replaced.


Cheers,
Tink


All times are GMT -5. The time now is 03:52 AM.