awk search and replace and overwrite file

hi,

i am doing

awk '{gsub("hello", "bye", $0); print}' test.dat

but I want to actually store the results of this global change into the file test.dat itself, i.e. I don't want the results to come to stdout, I want the results to overwrite the initial file

how can I do this?

thanks

With AWK you'll need something like this:

awk '{gsub("hello", "bye")}1' test.dat > test.dat_tmp && 
  mv test.dat_tmp test.dat

or this (not recommended):

{ rm test.dat && 
    awk '{gsub("hello", "bye")}1' > test.dat
  } < test.dat  

I would use Perl:

perl -i -pe's/hello/bye/g' test.dat  
1 Like

Or if your sed version supports the -i (inplace) option (check your manpage):

sed -i 's/hello/bye/g' test.dat

brilliant, thanks