How to preserve spaces in input fields with awk?

I'm trying to do something pretty simple but its appears more complicated than expected... I've lines in a text file, separated by the comma and that I want to output to another file, without the first field.

Input file:

file1,item,      12345678
file2,item,      12345678
file2,item,      12345678

In output I've got the following:

,item, 12345678
,item, 12345678
,item, 12345678

As you can see the spaces before 12345678 are kind of merged into one space only.

My code:

cat myfile | while read l_line
   do
      v_OutputFile=$(echo $l_line | awk -F',' '{print $1}')
      echo $(echo $l_line | awk -F',' '{OFS = ",";$1=""; print $0}') >> ${v_OutputFile}
   done

The issue seems to come from the echo command that removes the spaces. If I do an echo with the quotes it works well. For instance:

echo 'file1,item,          12345678' | awk -F, -v OFS="," '{$1="";print $0}'

But I could not find a solution to work this out with the while loop. Even by putting the quotes in my input file, it stills removes the spaces.

Thanks for your help !

Look here and ff. ( entire thread )

Try the awk script below...

awk -F"[ ]" '{s="";n=split($1,a,",");for(i=2;i<=n;i++) s = s ? s","a : ","a;$1=s;print}' file

Putting the quotes at the right places will make it work:

cat file | while read l_line; do echo "$(echo "$l_line" | awk -F',' '{OFS = ",";$1=""; print $0}')"; done
,item,      12345678
,item,      12345678
,item,      12345678
1 Like

Ok to use the printf but I still have to use the echo command so I assume it will still remove the spaces no ?

---------- Post updated at 01:16 PM ---------- Previous update was at 12:44 PM ----------

mmmhh yeah it does the trick. Don't know what I did wrong at the first place because I tried to do the same but I probably put the quotes badly.
Thanks for this simple workaround !

---------- Post updated at 01:17 PM ---------- Previous update was at 01:16 PM ----------

Thanks Shamrock it's a nice piece of code. I assume it's more powerfull to use such a syntax so maybe I'll integrate it into my script.

Actually code posted by RudiC is far better than what I posted with the exception of the cat...so here's my version of the awk posted by RudiC...

awk -F"," '{$1="";OFS=",";print}' file

In sed:

echo "file1,item,      12345678" | sed -e 's/^\([^,]*\)//'
,item,      12345678

There is no need to set OFS for every line of the file:

awk '{$1=x}1' FS=, OFS=, file

Why the grouping and the -e?

sed 's/[^,]*//' file

---
Another one for greps that support the -o option:

grep -o ',.*' file

@shamrock: Thanks, but too much honour! I just took the requestors script and corrected the quoting. And, you're right, that code can be simplified, e.g.

awk -F"," '{$1=""} 1' OFS="," file

or even

awk -F"," '!($1="")' OFS="," file