Question

First off, thank you for everyone's help in advance! I've been learning Unix in school and have been doing well up until this most recent homework assignment.

I'm trying to figure out what the best way to approach this particular part in my homework assignment.

I have a headers file which I must separate into two separate files. There are two parts to this part of the assignment:

First, the first two lines of the file go into one file. I did this by doing:

head -2 headers > file1

However, the next request is to take two column headers (--Regular-- and --Overtime--) and put them into another file...which is what I'm having trouble with.

The header file looks like this:

Merry Land Training Academy
Pay Report
Week of June 12, 1999

                --Regular---    --Overtime--    Gross   Net
Employee        Hours   Rate    Hours   Rate    Pay     Pay

I know that grep can only match lines that contain the pattern, however how can I remove characters after the last two -- in Overtime?

For example, my grep will return the following:

egrep 'Regular' headers

            --Regular---    --Overtime--    Gross   Net 

I know I could manually do a sed replace of "Gross" and "Net" after doing a grep to remove the words, however I know this is inefficient.

This command will be part of a script which will contain many other processes (which I have been able to do thus far).

In my research online, I know a lot of people recommend using awk, however we have not yet learned this in the course.

Again, thank you in advance. I really look forward to learning from everyone's experience.

Was it helpful?

Solution

Why do you think using sed would be inefficient? Certainly piping grep to sed would be a mistake, but sed is pretty good. You haven't really defined the problem very well, but assuming that you can distinguish a header by the existence of the string --, you could simply do:

sed -n -e '/--/s/[^-]*$//p' input > output

This will take all lines that contain -- and output everything up to the final -. If you only want to print the first such line:

sed -n -e '/--/{s/[^-]*$//p;q;}' input > output
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top