Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

awk Removing some spaces from the end of a column

I am trying to remove 2 spaces from the end of the second column of my file using this command:

awk -F '|', '{gsub(/[ \$]/, "", $2); print}' Myfile

The format of my input file looks like this (The characters and numbers here are just for showing the format):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   1AA       A      1   9.999   9.999   9.999
 111BB       B   1111   9.999   9.999   9.999
1111AABB  ABCD  11111   9.999   9.999   9.999

And I want the output like follows:

   1AA       A    1   9.999   9.999   9.999
 111BB       B 1111   9.999   9.999   9.999
1111AABB  ABCD11111   9.999   9.999   9.999

In practice, the third column shifts 2 spaces toward the second column.

But my code does nothing 🙁

Can anyone explain to me what’s the problem with my code?

Thank you in advance!

>Solution :

Your POSIX ERE [ \$] regex pattern matches one of three chars: a space, a backslash, or a $ char and is equal to [$\ ].

Since your file is fixed-width, you can use a GNU awk command like

awk 'BEGIN { FIELDWIDTHS="10 6 8 8 8 8" } {gsub(/  $/,"",$2); print $1 $2 $3 $4 $5}' Myfile > newMyfile

where / $/ matches two literal spaces at the end of the input ($ defines the end of string).

See more about FIELDWIDTHS in "4.6.1 Processing Fixed-Width Data" gawk manual.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading