1

I am attempting to run a shell script that loops through all files in a directory that I specify when executing the shell script, removes all commas in the file, and saves it as the same filename.

The problem is that it's deleting everything in each file, and I'm unsure why, but believe it has to do with "$filename";. I've tried putting it in brackets too, but I'm new to Bash.

I run it like so: NaN$ ./remove_commas.sh /path/to/dir

./remove_commas.sh

#!/bin/bash

dir="$@"

for filename in $dir/*; do
    echo "$filename"

    cat "$filename" | tr -d ',' > "$filename";
done
NaN
  • 643
  • 1
  • 8
  • 21
  • The `> "$filename"` actually happens before the `cat` and overwrites the content of the file! Save the output into a new file and use `mv` to replace the old one with the new one after the `tr` finishes. The other question I just linked looks like it has some answers that might help you (e.g., `sponge`). – cxw May 29 '19 at 15:20

1 Answers1

0

You can do it with sed, which has an option to write the result back to the input file.

sed -i 's/,//g' "$dir/*"
Barmar
  • 741,623
  • 53
  • 500
  • 612