Can I make `cut` change a file in place?

The moreutils package from ubuntu (and also debian) has a program called sponge, which sort-of also solves your problem.

From man sponge:

sponge reads standard input and writes it out to the specified file. Unlike a shell redirect, sponge soaks up all its input before opening the output file. This allows constricting pipelines that read from and write to the same file.

Which would let you do something like:

cut -d <delim> -f <fields> somefile | sponge somefile

You can't. Either use ed or GNU sed or perl, or do what they do behind the scenes, which is to create a new file for the contents.

ed, portable:

ed foo <<EOF
1,$s/^\([^,]*\),\([^,]*\),\([^,]*\).*/\1,\3/
w
q
EOF

GNU sed:

sed -i -e 's/^\([^,]*\),\([^,]*\),\([^,]*\).*/\1,\3/' foo

Perl:

perl -i -l -F, -pae 'print @F[1,3]' foo

cut, creating a new file (recommended, because if your script is interrupted, you can just run it again):

cut -d , -f 1,3 <foo >foo.new &&
mv -f foo.new foo

cut, replacing the file in place (retains the ownership and permissions of foo, but needs protection against interruptions):

cp -f foo foo.old &&
cut -d , -f 1,3 <foo.old >foo &&
rm foo.old

I recommend using one of the cut-based methods. That way you don't depend on any non-standard tool, you can use the best tool for the job, and you control the behavior on interrupt.


I don't think that is possible using cut alone. I couldn't find it in the man or info page. You can do something such as

mytemp=$(mktemp) && cut -d" " -f1 file > $mytemp && mv $mytemp file

mktemp makes you a relatively safe temporary file that you can pipe the cut output into.