LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Need help with Sed regex (https://www.linuxquestions.org/questions/linux-newbie-8/need-help-with-sed-regex-4175512390/)

Almaz 07-27-2014 12:07 AM

Need help with Sed regex
 
I can't find a way to delete everything after a character on the first occurrence.

I have:
first case: blahh123-blah-456 one two three
second case: 123-blah two 23 three

must be converted to

blah-456 one two three
blah two 23 three

so far I came up with the following regex, it only works for the first case but it doesn't work for the second one. I need sed to be able to remove all the characters before and including first sign "-"
Code:

echo "blahh123-blah-456 one two three" | sed 's/\(.*\)-\(.*-\)/\1foo39820\2/' | sed 's/^.*foo39820//'
Please point me to the right directions. Thanks in advance

jpollard 07-27-2014 12:12 AM

Wouldn't it be simpler since the desired removal is at the beginning of the line? "s/^blahhh123-//"

syg00 07-27-2014 12:19 AM

Only works for that specific case. The generic answer is to delete all non-minus characters up to the (first) minus character.
Character classes allow you define such a case - the doco describes this.

Almaz 07-27-2014 12:19 AM

Quote:

Originally Posted by jpollard (Post 5210165)
Wouldn't it be simpler since the desired removal is at the beginning of the line? "s/^blahhh123-//"

it's not constant

Almaz 07-27-2014 12:27 AM

In other words I really need to get this cleaned up. That's what I have

/tmp/var/log/messages.0-Jul 27 00:22:49 go.sonobi.com
/tmp/var/log/messages-Jul 27 00:22:49 kona.kon-tera.com
/tmp/var/log/messages.0-Jul 27 00:22:49 pagead2.googlesyndication.com
/tmp/var/log/messages-Jul 27 00:22:49 s.skimresources.com

I'm trying to make it look clean

Jul 27 00:22:49 go.sonobi.com
Jul 27 00:22:49 kona.kon-tera.com
Jul 27 00:22:49 pagead2.googlesyndication.com
Jul 27 00:22:49 s.skimresources.com

syg00 07-27-2014 12:50 AM

If one was slightly twisted this would work on that data - using a character class you could reduce it to 7 chars and make it completely independent of the actual text. Like I said, see the doco.
Code:

sed -r 's:^/tmp/var/log/messages(.0)*-::' some.input

Almaz 07-27-2014 01:03 AM

Thanks for all your help. It looks like I was trying to make it more complicated than it's really is. I just used a very basic method instead of complicated one :)

Code:

|sed 's/^.*messages[.]0-//' | sed 's/^.*messages-//'

sycamorex 07-27-2014 02:28 AM

Wouldn't it be simpler to use 'cut'? I haven't tested it but you could try:

Code:

cut -d'-' -f2- file

Almaz 07-27-2014 02:39 AM

Thanks a lot sycamorex and syg00 both methods works great. Never used cut option before but it's good to know now. I might even use it in the future.


All times are GMT -5. The time now is 04:28 AM.