-3

Input file:

123 exx abcdef 890 hello-hi-welcome and name in-India 1 3.45 1.3538 8.773
456 hfjgt 928 aetr-new-abc-India 1 9.7392 18.1903 8.752

Output:

123,exx abcdef,890,hello-hi-welcome and name in-India,1,3.45,1.3538,8.773
456,hfjgt,928,aetr-new-abc-India,1,9.7392,18.1903,8.752

How can we write a shell script for this?

  • It's not entirely clear what you're asking. – igal Oct 27 '17 at 13:02
  • @mallesh, What is your algorithm for deciding which spaces to keep and which to convert to commas? – glenn jackman Oct 27 '17 at 13:24
1

I think is it sufficient to change a space either before or after a digit:

$ sed -r 's/([[:digit:]]) /\1,/g; s/ ([[:digit:]])/,\1/g' file
123,exx abcdef,890,hello-hi-welcome and name in-India,1,3.45,1.3538,8.773
456,hfjgt,928,aetr-new-abc-India,1,9.7392,18.1903,8.752
| improve this answer | |
0

I suppose that you want to separate numbers and non-digit items in each line.

GNU awk solution:

awk -v FPAT='[0-9]+|[0-9]+\\.[0-9]+|[^0-9]{2,}' '{ 
           for(i=1;i<=NF;i++) { 
               gsub(/^ *| *$/,"",$i); printf "%s%s",$i,(i==NF? ORS:OFS) 
           } 
}' OFS=',' file

The output:

123,exx abcdef,890,hello-hi-welcome and name in-India,1,3.45,1.3538,8.773
456,hfjgt,928,aetr-new-abc-India,1,9.7392,18.1903,8.752
| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.