Delete the extra space after special character in all the lines of text file

407 views Asked by At

Following data represents 2 lines of text file:

1 2340: 2 1930: 1     
1 9: 3 4501: 1 45: 1 5620: 2

I want to delete the space after ":". So the output of above text file should be

1 2340:2 1930:1 
1 9:3 4501:1 45:1 5620:2
3

There are 3 answers

5
Alejandro Teixeira Muñoz On BEST ANSWER

You can use:

$ sed -e s"/: /:/g" file.dat
1 2340:2 1930:1     
1 9:3 4501:1 45:1 5620:2

EXPLANATION:

sed -e "COMMAND" will execute the command over file.dat`.

  • s says sed to Substitute
  • /: /:/ are the chain to substitute and the chain desired, separated by /.
  • Finally, g tells sed to be executed more than once time per line.

As @Tom commented, the quotes are better single quotes, and -e is not necessary, then:

$ sed 's/: */:/g' file.dat
1 2340:2 1930:1     
1 9:3 4501:1 45:1 5620:2

EDIT 2 As @josifoski commented, the * after the space char, will allow more than one space, not just one

You can read some sed docs here:

AWK GSUB

$ awk '{gsub(/: */,":"); print}' file.dat
1 2340:2 1930:1     
1 9:3 4501:1 45:1 5620:2
0
AKS On

Use the following: If you want to replace ":" character followed by single/multiple spaces (" " or "\t" aka tab character(s)).

sed -i "s/:[ \t][ \t]*/:/g" filename.txt

or If you just want to substitute ":" with only one visible space into ":"

sed -i "s/:[ \t]/:/g" filename.txt

PS:

  1. You can also use other characters for ex: ^ or # etc in place of / in sed command.
    For ex: sed -i "s#koba#loki#g" filename.txt.

  2. -i option (I used above) will update the file (i.e. in place update) instead of throwing the std output on screen. Don't use -i until you are sure, what you are updating. Taking a backup of the given file first, helps sometimes.

3
Ed Morton On
$ awk -F': ' -v OFS=":" '{$1=$1}1' file
1 2340:2 1930:1
1 9:3 4501:1 45:1 5620:2