Arun Antony
Arun Antony

Reputation: 593

How to use GREP/other commands in UNIX for stripping head and tail records from a text file

I have a flat file as given below. How do I delete the header and footer from the file which header starts with 'H:' and trailer starts with 'T:' using UNIX shell script(KSH) and rewrite the rest of the data into a different file?

H:20050427 HEADER RECORD
0000000 00000 000000000 123456 00 654321 DATARECORD
0000000 00000 000000000 123456 00 654321 DATARECORD
0000000 00000 000000000 123456 00 654321 DATARECORD
0000000 00000 000000000 123456 00 654321 DATARECORD
T:20050427 TRAILER RECORD

Upvotes: 1

Views: 3626

Answers (3)

glenn jackman
glenn jackman

Reputation: 247012

To remove the first and last lines: sed '1d;$d' file

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490398

Assuming what you've shown is reasonably representative of the other data (everything you want to keep starts with a number, and everything you want to get rid of starts with a letter), it should be pretty trivial, something like: grep "^[0-9]" inputfile > outputfile

Upvotes: 1

Mark Longair
Mark Longair

Reputation: 467601

To remove the first and last line, you could do:

 tail -n +2 input-file | head -n -1 > output-file

... or to just remove any lines beginning with 'H:' or 'T:' you could do:

 egrep -v '^[HT]:' input-file > output-file

Upvotes: 2

Related Questions