Remove characters from fixed length file

Hello

I've question on the requirement I am working on.

We are getting a fixed length file with "33" characters long. We are processing that file loading into DB.

Now some times we are getting a file with "35" characters long. In this case I have to remove two characters (in 22,23 positions) and process the file.

Here is the sample file. I need to remove "20" and process the remaining file.

Can you help achieving this task.I appreciate your help.

120000111LIFEWELC    20            $
120000222LIFEWELC    20            $
120000333LIFEWELC    20            $
120000444LIFEWELC    20            $

Thanks
Kind Regards
Vpadala

Hi manasvi24,

One way using perl:

$ perl -lpe 'if ( length == 35 ) { s/\A(.{21}).{2}/$1/ }' infile

Thank you so much for the quick turn around. Is there any way can I achieve this using Unix Awk/Sed.

Once again thanks in advance for your help.

Yes. Very similar using sed:

$ sed -e '/^.\{35\}$/ s/^\(.\{21\}\).\{2\}/\1/' infile

This is working fine. Thank you so much for helping me. I tried to understand the command.
If you don't mind can you help me understand what are we doing here in detail.

Thanks in Advance
VPadala

Thank you much Birei. This is so helpful. I really appreciate your help

Might I'm late but with awk

 awk  ' length > 20 {$0=substr($0,0,20); } 1' filename

Thanks for the response.. "Sed" is working fine. I this this awk didn't work...
Anyways can you please explain me the above "awk" command ? I appreciate your help.

Thanks
Kind Regards
VPadala

  1. length > 20 -- checks line length
  2. $0=substr($0,0,20) -- if step1 is true then do this action
    set line to first 20 characters
  3. Print the complete line.

withdrawn

@tarun - you need to read the full question

this awk will work for you.

 
awk 'length($0)==35{$0=substr($0,0,21)substr($0,24,35)}1' input.txt

Thank you. I really appreciate your help.This make sense.could you please tell me what does "1" doing here.

Thanks
VPadala

Hi,

please find..

Everything in awk has the form condition{action} . If the condition evaluates to 1 then the action is performed. If the condition is omitted then the default condition is 1, so the action is always performed. If the action is omitted then the default action is performed, which is {print $0} . In this case the condition is "1" so that evaluates to 1 and the action is omitted, therefore {print $0 } is performed, which is "print the entire record".

Thanks a ton. This is really helpful.