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):
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.