2

I have about 260 files in a directory. How can I input these files one by one into some thing like this
file is an array name

file=input stream of multiple files 
x=0

LOOP
tr -d '\r'  file2
rm $file
mv file2 $file
x=$x+1
LOOP ends
SamFlynn
  • 1,025

2 Answers2

2

Using a find one-liner:

find . -maxdepth 1 -type f -exec sh -c '< "{}" tr -d "\r" > "{}.processed"' \;

This will create a carriage-returns-stripped copy of each file in the current working directory named as the original file with a .processed extension.

tr can read only from stdin, so it can't edit files in-place natively, however one hack is to redirect the content of a file to the stdin of a subshell and to redirect it as a here string to tr's stdin, so that the file is read before the truncation necessary in order to write the file takes place:

find . -maxdepth 1 -type f -exec bash -c '<<< "$(< {})" tr -d "\r" > {}' \;
kos
  • 41,268
1

Using perl

perl -i -pe 'tr/\r//d' <your_file>

and with find for all files in your folder:

  • long version

    find <your_path> -maxdepth 1 -type f -print0 | xargs -I{} -0 perl -i -pe 'tr/\r//d' {}
    
  • short version

    find <your_path> -maxdepth 1 -type f -exec perl -i -pe 'tr/\r//d' {} \;
    

Example

$ printf "%s\n%s\n" "line 1" "line 2" > foo
$ printf "%s\r\n%s\n" "line 1" "line 2" > bar

$ hexdump foo
0000000 696c 656e 3120 6c0a 6e69 2065 0a32     
000000e

$ hexdump bar
0000000 696c 656e 3120 0a0d 696c 656e 3220 000a
000000f

$ perl -i -pe 'tr/\r//d' bar

$ hexdump bar
0000000 696c 656e 3120 6c0a 6e69 2065 0a32     
000000e
A.B.
  • 92,125