LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Replace a string with pattern within that string (https://www.linuxquestions.org/questions/linux-newbie-8/replace-a-string-with-pattern-within-that-string-934259/)

shreyas08 03-13-2012 01:34 PM

Replace a string with pattern within that string
 
I want to replace a part of string with a pattern within that string.

for eg:
if my string is "abcd#25 - efgh ijkl" it should print output as "abcd#efgh"

if my string is "xxxx#100 - yyyy zzzz" it should print output as "xxxx#yyyy"

The pattern is # followed by integer should be replaced with first word after # integer -

Sorry for my bad english.

sycamorex 03-13-2012 02:20 PM

Try the following:
Code:

sed 's/\(.*#\).*- \(.*\) \(.*\)/\1\2/' file
See if that's what you want.

David the H. 03-13-2012 03:27 PM

Use the -r option to remove the need to backslash everything.

Code:

sed -r 's/(.*#).*- (.*) (.*)/\1\2/' file
With grep and sed, their basic regular expressions level treats parens and many other regex characters as literal. But as a gnu extension you can backslash escape them to enable their special meanings.

But when you use the extended regular expressions (sed -r/grep -E/egrep), everything is reversed. All regex characters are enabled by default, and escaping disables them.

Check out the grep man page for details (and the info page for even more).

sycamorex 03-13-2012 03:31 PM

Quote:

Originally Posted by David the H. (Post 4625997)
Use the -r option to remove the need to backslash everything.

Code:

sed -r 's/(.*#).*- (.*) (.*)/\1\2/' file
With grep and sed, their basic regular expressions level treats parens and many other regex characters as literal. But as a gnu extension you can backslash escape them to enable their special meanings.

But when you use the extended regular expressions (sed -r/grep -E/egrep), everything is reversed. All regex characters are enabled by default, and escaping disables them.

I keep forgetting about the existence or ERE:)

grail 03-14-2012 12:07 AM

Code:

awk -F"[ #]" '{print $1"#"$4}' file


All times are GMT -5. The time now is 11:51 PM.