Iterate over files in a folder

Iterate over files in a folder

I have a folder containing files, and I need to iterate over them using unix command "tr" having as output the same name as before (if is possible) (the code below doesn't work):

FILES=/root/Desktop/prova/*
for f in $FILES ; do
    echo "Processing $f file..."
    cat $f | tr "\n" "," > $f.tmp & mv $f.tmp $f 
done

I don't understand how can I use this command cat "$f" | tr "\n" "," > "$f" and redirect the output of each files. Then I should use another for loop to create N tool commands and run together. Have you any advice for loops studies?

答え1

The cat is a useless waste of CPU, eliminate it. Send the output instead to a temporary file, and rename that file back afterwards:

tr x y < input > input.tmp && mv input.tmp input

With moreutils installed, this may be done with sponge (which does the temporary file stuff behind the scenes):

tr x y < input | sponge input

Note that such renames may destroy fancy ACL or security contexts set on the now dearly unlinked original input file.

関連情報