Skip to content

Instantly share code, notes, and snippets.

@bekce
Last active October 22, 2021 10:32
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bekce/8de3fe6fe369aaabfaa811d3283a2b6c to your computer and use it in GitHub Desktop.
Save bekce/8de3fe6fe369aaabfaa811d3283a2b6c to your computer and use it in GitHub Desktop.
NTFS filename fix

If you happen to write to NTFS partitions using non-windows operating systems (such as with ntfs-3g, see this thread for more info), some of your files may have got written containing invalid characters in their names. When such a thing happen, the fix of chkdsk is just to delete them but clearly no one would ever want to have their files deleted to 'fix'!

This little script that I wrote aims to fix the invalid NTFS characters in batch and automatically by renaming the files with invalid characters to valid ones. It only fixes the characters in this set: <>:"\|?* which is pretty enough for most of the problems, but for advanced cases (like reserved names 'com', 'lpt') you must fix manually. Always double check the batch mv commands before running.

Fallacies:

  • Does not fix reserved names in Windows (like CON, PRN, AUX, NUL, COM1, COM2, etc).
  • Does not fix other illegal combination of characters like 'directory name cannot end with space or dot', etc.
  • Does not fix maximum path length problems.
  • To fix invalid directory names you must execute double times: first to fix folders only by using -type d param for find then to fix files.
  • It won't escape ' (single-quote) character in filenames.
# find the files with invalid names and write them to a file
find directory | grep '[<>:"\|?*]' > s-invalid.txt
# fix the file names
cat s-invalid.txt | tr '<>:"\|?*' '_' > s-fix.txt
# prepare the mv commands to execute
paste s-invalid.txt s-fix.txt | awk -F '[\t]' '{print "mv \047"$1"\047 \047"$2"\047"}' > s-cmd.txt
# execute them (double-check before executing)
sh s-cmd.txt
@bekce
Copy link
Author

bekce commented Feb 13, 2017

Quickfix for the current directory

find . | grep '[<>:"\|?*]' > s-invalid.txt
cat s-invalid.txt | tr '<>:"\|?*' '_' > s-fix.txt
paste s-invalid.txt s-fix.txt | awk -F '[\t]' '{print "mv \047"$1"\047 \047"$2"\047"}' > s-cmd.txt
sh s-cmd.txt
rm s-cmd.txt s-fix.txt s-invalid.txt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment