Home > Blockchain >  Remove leading space in each field when more than one field in one record
Remove leading space in each field when more than one field in one record

Time:03-24

I have a test data looking like this:

 Big, Data

where there is leading spaces in front of "Big" and "Data", and this record uses comma as a field separator. I am new in bash and i wanted to use awk to separate each field in each record and loop through them to strip leading zeros, and then output as a new file. My current script is as below, and received errors as below too. Any ideas will be highly appreciated!

awk 'BEGIN {FS=","}{for(i=1;i<=NF;i  ) $i=${${i}## (0)}; print$i}' input.txt > output.txt

Desired output(might be a bit hard to visualize but no leading spaces):

Big,Data

Error:

awk: syntax error at source line 1
 context is
    BEGIN {FS=","}{for(i=1;i<=NF;i  ) >>>  $i=${ <<<
awk: illegal statement at source line 1
awk: illegal statement at source line 1
    2 missing }'s

Reference for removing leading space in Bash here

CodePudding user response:

Your example doesn't appear to relate to your question, but perhaps awk 'BEGIN{FS=OFS=","}{for(i=1;i<=NF;i ) gsub("^0 ","", $i); print}' file.txt > newfile.txt will solve your problem.

E.g.

cat test.txt
000194513,00000001535,123415, 0, test

awk 'BEGIN{FS=OFS=","}{for(i=1;i<=NF;i  ) gsub("^0 ","", $i); print}' test.txt
194513,1535,123415, 0, test

CodePudding user response:

It's not clear what you want and your example has not zeros at all, so just guessing

awk -F, '{printf("%d, %d\n", $1, $2);}' input.txt

should remove the leading 0's

  • Related