Bash – How to insert whitespace between characters of words in a specific field in a file

awkbashprocessing-efficiency

I have a file containing 100000 lines like this

1 0110100010010101
2 1000010010111001
3 1000011001111000
10 1011110000111110
123 0001000000100001

I would like to know how can I display efficiently just the second field by adding whitespaces between characters.

0 1 1 0 1 0 0 0 1 0 0 1 0 1 0 1
1 0 0 0 0 1 0 0 1 0 1 1 1 0 0 1
1 0 0 0 0 1 1 0 0 1 1 1 1 0 0 0
1 0 1 1 1 1 0 0 0 0 1 1 1 1 1 0
0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 1

One solution would be to get the second column with awk and then add the whitespaces using sed. But as the file is too long I would like to avoid using pipes. Then I'm wondering if I can do that by just using awk.

Thanks in advance

Best Answer

is this ok?

awk '{gsub(/./,"& ",$2);print $2}' yourFile

example

kent$  echo "1 0110100010010101
2 1000010010111001
3 1000011001111000"|awk '{gsub(/./,"& ",$2);print $2}'
0 1 1 0 1 0 0 0 1 0 0 1 0 1 0 1 
1 0 0 0 0 1 0 0 1 0 1 1 1 0 0 1 
1 0 0 0 0 1 1 0 0 1 1 1 1 0 0 0

update

more than 2 digits in 1st column won't work? I didn't get it:

kent$  echo "133 0110100010010101
233 1000010010111001
333 1000011001111000"|awk '{gsub(/./,"& ",$2);print $2}'
0 1 1 0 1 0 0 0 1 0 0 1 0 1 0 1 
1 0 0 0 0 1 0 0 1 0 1 1 1 0 0 1 
1 0 0 0 0 1 1 0 0 1 1 1 1 0 0 0 


gsub(/./,"& ", $2)

1 /./  match any single character
2 "& " & here means the matched string, in this case, each character
3 $2   column 2

so it means, replace each character in 2nd column into the character itself + " ".