1

I have a directory full of output files, with files with names: file1.out,file2.out,..., fileN.out.

There is a certain key string in each of these files, lets call it keystring. I want to replace every instance of keystring with newstring in all files.

If there was only one file, I know I can do:

awk '{gsub("keystring","newstring",$0); print $0}' file1.out > file1.out

Is there a way to loop through all N files in awk?

megamence
  • 335
  • 2
  • 10
  • Does this answer your question? [Run shell script for every file in directory](https://stackoverflow.com/questions/10259836/run-shell-script-for-every-file-in-directory) – tripleee Jan 14 '21 at 09:31

2 Answers2

3

You could use find command for the same. Please make sure you run this on a test file first once it works fine then only run it in your actual path(on all your actual files) for safer side. This also needs gawk newer version which has inplace option in it to save output into files itself.

find your_path -type f -name "*.out" -exec awk -i inplace -f myawkProgram.awk {} +

Where your awk program is as follows: as per your shown samples(cat myawkProgram.awk is only to show contents of your awk program here).

cat myawkProgram.awk
{
  gsub("keystring","newstring",$0); print $0
}


2nd option would be pass all .out format files into your gawk program itself with -inplace by doing something like(but again make sure you run this on a single test file first and then run actual command for safer side once you are convinced by command):

awk -i inplace '{gsub("keystring","newstring",$0); print $0}' *.out
AsukaMinato
  • 1,017
  • 12
  • 21
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
1

sed is the most ideal solution for this and so integrating it with find:

find /directory/path -type f -name "*.out" -exec sed -i 's/keystring/newstring/g' {} +

Find files with the extension .out and then execute the sed command on as many groups of the found files as possible (using + with -exec)

AsukaMinato
  • 1,017
  • 12
  • 21
Raman Sailopal
  • 12,320
  • 2
  • 11
  • 18