replace spaces/tabs with delimiter |

Hi,

I'm looking for a command that replaces spaces/tabs with pipe symbol and store the result to the same file instead of routing it to another file.

infile

outfile

Thanks.

Try:

perl -i -pe 's/[ \t]/|/g;s/$/|/' file

What about consecutive spaces/tabs? One pipe symbol for any or one for each sequence?

First case:

sed 's/[<spc><tab>]/|/g' /path/to/source > /path/to/target

Second case:

sed 's/[<spc><tab>][<spc><tab>]*/|/g' /path/to/source > /path/to/target

This cannot be done with any stream-oriented tool (sed, awk, ...). Just move the result file in place of the source file afterwards:

sed '<somecommand>' /path/to/source > /path/to/target
mv /path/to/target /path/to/source

Replace "<spc>" and "<tab>" with literal space and tab characters in the above code.

I hope this helps.

bakunin

printf '%s\n' '1,$s/[<space><tab>]/|/g' w q | ed -s file >/dev/null

If you like living dangerously (although I wouldn't recommend it):

(rm file; sed 's/[<space><tab>]/|/g' > file) < file

If using the C/POSIX locale, you can use [[:blank:]] instead of [<space><tab>].

Regards,
Alister

Sorry but this command fails for multiple spaces/tabs.

$ cat file
asd asdf
sdgf            aasdf

$ ruby -ne 'puts $_.split.join("|")' file
asd|asdf
sdgf|aasdf

Sorry but my machine doesnt supports ruby command.

Surely this is false, what about:

sed -i 's/[[:blank:]]/|/g' file

Thanks, but this command replaces each space/tab with a delimiter which i dont expect. And i have removed the i option as it is not supported in my machine.

While that may be convenient, it's not doing anything in place. It creates a temp file and then clobbers the original with it. It's just a shortcut for the procedure in the post to which you are responding.

If you truly want to do it in place, you'll need to use something like ed or ex.

Regards,
Alister

I managed to do it with this command

Thanks Alister, I was not aware of the -i implementation detail, which is interesting. :b:

I like your passing of commands to ed to perform the edit, which seems very natural - use the editor to make edits. But I wonder why the -i implementation did not do something similar. Moreover, why all sed versions do not have this feature is strange.