Help with awk or sed Command to Replace Text in Files

Hello Everyone,

I have many files like so:

file1.txt
file2.txt
file3.txt

Within each file I have many lines of random text separated by commas like so:

abcAAA,123,defAA,456777,ghiA,789
jklB,101,mnoBBB,11211,pqrB,13111
stuCC,415,vwxCCCC,161,yzaC,718

I am trying to use SED or AWK to replace the 4th column with XXX on each line in each file so the result would be:

The same files like so:

file1.txt
file2.txt
file3.txt

Now within each file:

abcAAA,123,defAA,XXX,ghiA,789
jklB,101,mnoBBB,XXX,pqrB,13111
stuCC,415,vwxCCCC,XXX,yzaC,718

I have a workaround that I've come up with but it combines all the files into one file, unfortunately. (I need the files to be edited in place)
Here is my attempt:

cat *.txt | awk -F, '{print $1 "," $2 "," $3 ",XXX," $5 "," $6}' > result_file.txt

One approach is to use a for loop to open one file at a time, modify and redirect the output to a temporary file, rename the temporary file back to original file:-

for file in *.txt; do awk -F, '{$4="XXX"}1' OFS=, $file > tmp; mv tmp $file; done
1 Like

Thank you, Yoda! I will give this a try and update this thread as solved if I can get it working. :slight_smile:

--- Post updated at 11:08 PM ---

In my initial tests the solution is almost perfect but I am getting an extra line in my files:

sdf,asdf,XXX,asdf,asdf
sdf,asdf,XXX,asdf,asdf
sdf,asdf,XXX,asdf,asdf
sdf,asdf,XXX,asdf,asdf
,,XXX

I am working out why this is and I will update.

Looks like you have a trailing empty line in your file. And, you seem to replace $3 now, not $4.

1 Like

Correct! Getting rid of the extra line fixed it. I was playing around with different column positioning that's why I had 3 instead of 4.

Thank you all! I will now mark this as solved!