Home > front end >  How to redirect output for change specific csv column and write into same file. Logically: awk '
How to redirect output for change specific csv column and write into same file. Logically: awk '

Time:10-14

I need to change specific columns on my csv file and awk command is doing my job.

awk 'BEGIN{FS=OFS=","} {$19 = $1} 1' a.csv

But it prints the result and i need to save it to same file to use the file later.

what i've tried:

awk 'BEGIN{FS=OFS=","} {$19 = $1} 1' a.csv > a.csv but it deleted all content.

CodePudding user response:

GNU awk:

awk -i inplace 'BEGIN{FS=OFS=","} {$19 = $1} 1' a.csv > a.csv

any awk:

tmp=$(mktemp) &&
awk 'BEGIN{FS=OFS=","} {$19 = $1} 1' a.csv > "$tmp" &&
mv -- "$tmp" a.csv

The latter works for any command. You can't just do cmd file > file because your shell can do the > file part first to init the output file and then when it tries to run the cmd file part file is already empty as you experienced. The &&s are required to ensure the current step succeeded before you do the next step otherwise you could end up zapping your input file and losing all it's contents if mktemp or awk failed for some reason.

  • Related