Skip to main content
edited tags
Link
Jeff Schaller
  • 68.8k
  • 35
  • 122
  • 265
Source Link

How do I use grep, awk, or sed to get a substring of a line up until a string literal?

I am trying to process a text file and omit a certain string literal if it occurs at the end of the line. E.g.:

Source:

ABC 123
DEF, characters I don't want
GHI, these characters are ok

Desired Output:

ABC 123
DEF
GHI, these characters are ok

If I do grep -v ', characters I don't want$', it omits that entire line.

I can't do a simple awk column since I want the , these characters are ok substring

I can't use cut to split on a delimiter because the delimiter needs to be multiple characters (, characters I don't want).

With Python it would be super simple with something like: string.split(", characters I don't want", 1)[0]

(Tangentially, I'm wondering in which use cases it really is preferable to use grep, awk, or sed in complicated situations like this vs Python when Python is so much more readable and maintainable.)