Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

The man page doesn't give me much hope, but I'm hoping it's an undocumented (and/or GNU-specific) feature.

share|improve this question

3 Answers 3

up vote 10 down vote accepted

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):

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

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

cp 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.

share|improve this answer

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.

share|improve this answer

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
share|improve this answer
    
Really cool utility. :) –  balki Jan 14 '11 at 17:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.