Remove space before numbers in delimited file

Hi,

I have a file which looks like this

FORD|1333-1| 10000100010203| 100040507697|0002|356.45|5555| SSSSY|KKKKM|1000005|10| N096|10043| C987

I need the output to look like this

FORD|1333-1|10000100010203|100040507697|0002|356.45|5555| SSSSY|KKKKM|1000005|10| N096|10043| C987

The leading space before 10000100010203 and 100040507697 is removed but the space before SSSSY,N096 and C987 is preserved.

So algorithm is remove space before numbers only.
I'm using sed to search for '| ' but not sure how to look only for pure numbers.

Please advice

sed 's/ \([0-9]\)/\1/g'

Hi,

The command will fail when it encounters a field starting with number but having characters like

FORD| T976| 7XYZ| 567

will be converted to

FORD| T976|7XYZ|567

7XYZ is affected.

I forgot to mention this combination in my earlier post, sorry about that.

sed 's/ \([0-9][0-9]\)/\1/g'

That might fail on 66XYZ . How about

sed 's/ \([0-9]*|\)/\1/g' file
1 Like

That will fail on the last field. The following adds a | then substitutes then removes the |

sed 's/$/|/; s/ *\([0-9.]*|\)/\1/g; s/|$//'

Or try per field processing with awk:

awk '{for(i=1; i<=NF; i++) if(/^ / && $i==$i+0) $i+=0}1' FS=\| OFS=\| file

Hmmmm - with my mawk:

FORD|1333-1|1.00001e+13|1.00041e+11|0002|356.45|5555| SSSSY|KKKKM|1000005|10| N096|10043| C987

---------- Post updated at 07:52 ---------- Previous update was at 07:49 ----------

Small adaption:

awk '{for(i=1; i<=NF; i++) if(match($i, /^ /) && $i==$i+0) sub(/^ /, "", $i)} 1' FS=\| OFS=\| file
[FORD|1333-1|10000100010203|100040507697|0002| 7XYZ|5555| SSSSY| 66KKKKM|1000005|10| N096|10043| C987
1 Like

Yes, I meant to write:

awk '{for(i=1; i<=NF; i++) if($i~/^ / && $i==$i+0) $i+=0}1' FS=\| OFS=\| file

otherwise, something like:

awk '{for(i=1; i<=NF; i++) if($i~/^ +[0-9]+$/) sub(/^ +/,x,$i)}1' FS=\| OFS=\| file