Mikhail R. Mikhail R. - 3 months ago 13
Bash Question

Output redirection to the same file without a temporary file

Let's say I have a tab-delimited data file. I would like to convert every tab in the file to a single space character.

$ cat junk
John Doe 35 New York
Bob Smith 24 Boston
Jane Doe 31 Los Angeles


To do that, I can use the
expand
command. If I do it like this:

$ expand -t 1 junk > junk


it will clobber the junk file and all the data will be lost. The simplest solution that comes to mind is, of course, redirect the output to a temporary file and then redirect the output from the temporary file back to the original one. That would look something like this:

$ expand -t 1 junk > temp
$ cat temp > junk
$ rm temp
$ cat junk
John Doe 35 New York
Bob Smith 24 Boston
Jane Doe 31 Los Angeles


I think this is too much hassle. Maybe there's a simpler way that I could use to do the whole thing in one go?

Answer

If you have GNU sed (the question is tagged linux so that probably is the case), you can use its -i or --in-place option which deletes its temporary files (unless you provide a backup suffix).

Use the s (substitute) command to replace each tab with a space; the g (global) modifier replaces all tab characters on the line being processed, i.e., not just the first tab character:

sed -i 's/\t/ /g' junk