I have a list of filenames similar to the following:
NAME - Something something something
ANOTHER NAME - More stuff
THIRD - This is a title
FOURTH - This is a title - With an extra hyphen
FIFTH NAME - And some more
What I would like is to grab just the names up to the first hyphen. That is, my results should be:
NAME
ANOTHER NAME
THIRD
FOURTH
FIFTH NAME
I was able to accomplish this via cut -d'-' -f1
but I was wondering what would be a way to translate this into a grep
command?
I have tried expressions like grep -o "^[[:upper:]]* -"
but I run into issues when there is a second hyphen contained in the name (e.g. FOURTH
) and also with names that have more than word (e.g. ANOTHER NAME
and FIFTH NAME
).
You can use the extended flavour, use anchor to the beginning of the line and match every character until if finds a dash, like:
grep -oE '^[^-]*' infile
It yields:
NAME
ANOTHER NAME
THIRD
FOURTH
FIFTH NAME