Use tr to remove line breaks in multiple files?

Ted Maclin picture Ted Maclin · Oct 7, 2014 · Viewed 8k times · Source

I have a set of several hundred .txt files that I am analyzing (ngram analysis using NSP), and I need to remove all the line breaks from each file. I can do it one at a time using tr:

$ tr -d "\n\r" < input1.txt > output1.txt

How can I do this for my entire directory of files at once?

Answer

Nick Russo picture Nick Russo · Oct 7, 2014

This will add -out before .txt. You haven't specified what the filenames are like, other than .txt, so hopefully you don't have input files named foo-out.txt, etc.

for f in *.txt
do
  tr -d "\n\r" < "$f" > $(basename "$f" .txt)-out.txt
done