1

I have a CSV file that looks like this:

Wave 1,bob,IL
Wave 2,julia,CO
Wave 1,mark,WA
Wave 2,fred,AK

I want to change it to look like this:

Wave 1,bob
Wave 2,julia
Wave 1,mark
Wave 2,fred

I can use use cut -d ',' -f 1-2 test.csv to produce this result in stdout but I need to output to the same file being cut. I have tried cut -d ',' -f 1-2 test.csv > test.csv and stdbuf -o0 cut -d ',' -f 1-2 test.csv > test.csv but they both produce blank test.csv files.

How can I remove everything after the second comma on a per line basis, and write the result in-place?

user5104897
  • 155
  • 1
  • 11
  • Possible duplicate of [sed command find and replace in file and overwrite file doesn't work, it empties the file](http://stackoverflow.com/questions/5171901/sed-command-find-and-replace-in-file-and-overwrite-file-doesnt-work-it-empties) – Benjamin W. Mar 14 '17 at 22:02
  • Off the beaten path, you could use [`sponge`](http://manpages.ubuntu.com/manpages/xenial/en/man1/sponge.1.html) to write to the input file. – glenn jackman Mar 15 '17 at 02:07

5 Answers5

4

There is no such thing as real "inplace" editing with any UNIX tool*, they all use tmp files behind the scenes. Keep it simple:

cut -f1,2 file > tmp && mv tmp file

*exceptions: ed uses an internal buffer the size of the original file instead of a tmp file and dd CAN be used to do inplace editing but is not for the faint of heart (see https://stackoverflow.com/a/17331179/1745001).

Community
  • 1
  • 1
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
2

If you have gnu awk 4.1.0+ then it has support of in place editing using -i inplace option:

gawk -i inplace 'BEGIN{FS=OFS=","} {print $1, $2}' file

cat file
Wave 1,bob
Wave 2,julia
Wave 1,mark
Wave 2,fred
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    And if you're on something else than GNU awk 4.1.0+ , see [this](http://stackoverflow.com/a/16529730/4162356). – James Brown Mar 15 '17 at 05:28
2

Just for the record, this is how can be done with cut that you have been trying to:

cut -d, -f1-2 <<<"$(<file1)" >file1

Or

cut -d, -f1-2 file1 |tee file1
George Vasiliou
  • 6,130
  • 2
  • 20
  • 27
0
awk '{sub(/,..$/,"")}1' file

Wave 1,bob
Wave 2,julia
Wave 1,mark
Wave 2,fred
Claes Wikner
  • 1,457
  • 1
  • 9
  • 8
0
sed 's/,/\n/2;P;d' file

1. replace the 2th "," as "\n"

2. use P to print up to the 1th "\n"

3. delete the pattern space

mop
  • 423
  • 2
  • 11