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
3
  • You can do in-place edit, perl -i -pe 'tr|\r||d' files* and it is faster than repeated fork of tr command.
    – mpapec
    Jun 23 '15 at 6:44
  • So basically you wanna delete all \r from each file in a directory ? Jun 24 '15 at 9:37
  • Yes. That's what I want to do.
    – SamFlynn
    Jun 24 '15 at 9:41
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" > {}' \;
0
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.