Remove last few characters in a file but keeping Header and trailer intact

Hi All,

I am trying write a simple command using AWK and SED to this but without any success.

Here is what I am using:

head -1 test1.txt>test2.txt|sed '1d;$d' test1.txt|awk '{print substr($0,0,(length($0)-2))}' >>test2.txt|tail -1 test1.txt>>test2.txt

Input:

Header
1234567
abcdefgh
trailer

Output:

Header
12345
abcdef
trailer

Any help on this would be highly appreciated.

Thanks,

awk 'FNR==1{pre=$0;next}{print pre;pre=substr($0,1,length($0)-2)}END{print}' file

FNR means File Number of Record (line number). So for first line we set variable pre to be the line, and next skips to next line. Then for every successive line, we print are printing the previous line. Using END we can print the trailer unmodified.

sed:

sed '1n;$n;s/..$//' infile