Help with removal of blank spaces from the second field!

Hi everyone..
I'm trying to eliminate multiple whitespaces from a file..
I must make use of shell script to eliminate whitespaces..
Take a look at the sample file

 
1 int main() 
2  { 
3 int a,b; 
4    printf("Enter the values of a and b"); 
5      scanf("%d%d",&a,&b); 
6 if(a>b) 
7        printf("a is greater"); 
8   else 
9 printf("b is greater"); 
10 return(0); 
11  } 

The numbers indicate the line number..
The line numbers are followed by one or more spaces.
So I have to eliminate multiple spaces..
ie my output file should be as shown below

 
1 int main() 
2 { 
3 int a,b; 
4 printf("Enter the values of a and b"); 
5 scanf("%d%d",&a,&b); 
6 if(a>b) 
7 printf("a is greater"); 
8 else 
9 printf("b is greater"); 
10 return(0); 
11 } 

I should do this without disturbing the numbers..
Note: The numbers might not be in sequence!
So how can I do this??
Any idea of how to proceed??
Thanks in advance!

Hi,

Try next 'Perl' instruction:

$ perl -lape 's/^(\d+)\s*(.*?)\s*$/$1 $2/' infile

Regards,
Birei

1 Like

Hi thank you!!
But isn't it possible to do the same using sed command??

Although this smells like homework, here is your solution:

sed 's/\(\d*\)  */\1 /'
1 Like
sed 's/\([^ ]*\) *\(.*\)/\1 \2/' file
1 Like

Or (only 1 pattern to remenber):

 sed -e 's/\([^ ]\{1,\} \) */\1/' file

Thank you! :slight_smile:

---------- Post updated at 01:47 PM ---------- Previous update was at 01:47 PM ----------

Thank you! :slight_smile: