1

example line:

04/07/2016 11:23:44 [8344] BDFDD123A Some Text Here (Word: ABD_ABDCD, Word: Word, Word: Word Word-ABCAbcAbc-HOSTNAME.DOMAINNAME.COM-ASDF).

I'd like to extract the "HOSTNAME.DOMAINNAME.COM-ASDF" part.

There is always a "-" before the "HOSTNAME" part and the line always ends with "." but not always ")."

It seems like if I could say for each line 1.) find the string ".COM" 2.) then go back to the previous "-" and forward to the next "." and give me everything in between that would work... but I have no idea how to do that.

Normally I would try to split by some sort of separator but it's not the same number of separators for every line. any idea how to tackle this?

1

Using grep with PCRE (-P):

grep -Po -- '-\K[^-]+\..*?(?=(?:\)|)\.$)' file.txt
  • - matches a - and \K discards the match

  • [^-]+\..*? matches the desired substring

  • The zero width positive lookahead pattern (?=(?:\)|)\.$) ensures the match is followed by ). or just . at the end of the line.


Example:

$ grep -Po -- '-\K[^-]+\..*?(?=(?:\)|)\.$)' <<<'04/07/2016 11:23:44 [8344] BDFDD123A Some Text Here (Word: ABD_ABDCD, Word: Word, Word: Word Word-ABCAbcAbc-HOSTNAME.DOMAINNAME.COM-ASDF).'
HOSTNAME.DOMAINNAME.COM-ASDF
0

If you want to keep the -ASDF part then

sed -E 's/.*-(.*-[^)]*)\)?\.$/\1/'

If you don't care about the -ASDF part then it's simpler

sed 's/.*-\(.*\)-.*/\1/' x   

This works by being "greedy" in the first .*

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.