Using cut without having to rename file

I am using the cut command as follows:

cut -d " " -f 3 file.dat > file_.dat

Is there a way to not have to rename the file, so that the result is actually written into file.dat directly within the cut-command? I could do a mv file_.dat file.dat, but that would be an additional step.

Something like this should do (didn't test it):

perl -i -lane 'print $F[2]' file.dat

There's not a 1-step way to do that unless the application's actually designed to do that, and most aren't. cut isn't. Those that are frequently side-effects.

sed -i, for instance, can change the ownership and permissions of the files it operates on because it's two steps -- create new file, replace the old. Run sed -i on a user as root, it'll replace the user-owned file with one owned by root!

I'm curious. Why do you even care about a subsequent mv step? Is there some constraint in play that you neglected to mention?

In case you've suffered mv-trauma in the past and it's in your best mental-health interests to avoid it, I suppose you could 'cat file_.dat > file.dat; rm file_.dat`. Technically, that does not involve any renaming.

There's also the unlink trick, which leverages the kernel's unwillingness to deallocate a file so long as a process maintains an open descriptor on it, even when that file no longer exists as an entry in the filesystem:

{ rm file.dat; cut -d " " -f 3 > file.dat; } < file.dat

Although that doesn't really save you any work. It still creates a new file and a new entry must be linked into the directory (the inode number for file.dat changes) and it still needs to fork/exec another utility to get the job done (rm). Worse, it creates a small window during which a system failure will leave you without any version of the data, and a larger window during which you'll have only a partially complete version of the data.

Are you feeling lucky? :wink:

Regards,
Alister

HI.

The thread at Sed does not make changes in the file but to the standard output demonstrates a Linux utility, sponge, and a perl work-alike that writes on the input file safely if desired -- it collects the output until EOF, then re-writes the file as specified. The cost is the time and space needed to collect the data on a temporary file and copy that file.

That is a solution that can be applied to this general class of problems.

Best wishes ... cheers, drl

Thanks all for your answers. I will settle for an additional mv command, since it is the easiest to understand for a novice programmer.