How to extract characters before a pattern

Viewed 73

I need some help on how to extract a specific string of a line.

I have a file with thousands of lines like this:

Eukaryota; Alveolata; Ciliophora; Intramacronucleata; Paramecium#
Eukaryota; Viridiplantae; Streptophyta; Embryophyta#
Bacteria; Cyanobacteria; Synechococcales; Acaryochloridaceae; Acaryochloris#
Eukaryota; Viridiplantae# 
Bacteria; Proteobacteria; Alphaproteobacteria#

And I would like to obtain the first and the last item of each line. So the output would be:

Eukaryota; Paramecium#
Eukaryota; Embryophyta#
Bacteria; Acaryochloris#
Eukaryota; Viridiplantae# 
Bacteria; Alphaproteobacteria# 

I know how to get the 1st column with

awk '{print$1}' fileIn > fileOut

but I don't know how to get the last item as it is always in different columns.

I tried adding the # and then just keep XX characters before the # with

grep -E -o '.{X,X}PATTERN. fileIn > fileOut

where the output looks like: les; Sulfolobaceae; Sulfolobus# ; Thermoproteaceae; Caldivirga# les; Haloferacaceae; Haloferax# Haloferacaceae; Haloquadratum# ales; Natrialbaceae; Natrialba#

But then I have to repeat the procedure and remove ; until I'm left only with the final item.

I've search to see if there is any grep or awk option to do that, extract 1st and last column or extract just the characters attached to # but I could not find any that work for me.

I would appreciate any suggestions on how to proceed.

Thanks.

4 Answers
Related