Hello
I have lot of textfiles written in vim editor. They are stored in multiple directories. Some have .txt extension and others have none. Reading them in linux is no problem. But when i try to open them in MS-Windows or smartphone, and because so many files have no .txt extension, it would ask to associate files with any program.
so i wrote a shell script to append .txt extension and also do some extra work for all files UNDER a directory.
The script is as follows:
Code:
#!/bin/bash
# Script Name: textren
# Renames text files.
# This shell does the following to files in a folder:
# 1) Check if the file is ASCII text.
# 2) Converts filename to lower case.
# 3) Replaces multiple spaces with single _.
# 4) Check if .txt extension exist, else append .txt extension.
for f in *; do
# Check if 'f' is a file, and then check if it is a text file.
if [[ -f "$f" && $(file "$f" | grep 'ASCII text$') ]]; then
# Convert to lower case
fLower="${f,,}";
# Replace multiple spaces with single underscore
fReplace="$(echo $fLower | sed 's/ */_/g')";
# Find length of file
length=${#fReplace};
# Target file Add/Replace .txt extension
if [[ "${fReplace:(( $length - 4 )):4}" != ".txt" ]]; then
fTarget="$fReplace.txt";
else
fTarget="$fReplace";
fi
mv -nv "$f" "$fTarget" 2>/dev/null
fi
done
OUTPUT: (Before):
Code:
$ ls -1
chrome plugins.txt
ffmpeg
Firefox-Plugins
git
mencoder.txt
nautilus DEL key
OPTIPING.TXT
pngcrush
thunderbird
Thunderbird 5 Shortcuts.pdf
tmux
OUTPUT: (After)
Code:
$ textren
‘chrome plugins.txt’ -> ‘chrome_plugins.txt’
‘ffmpeg’ -> ‘ffmpeg.txt’
‘Firefox-Plugins’ -> ‘firefox-plugins.txt’
‘git’ -> ‘git.txt’
‘nautilus DEL key’ -> ‘nautilus_del_key.txt’
‘OPTIPING.TXT’ -> ‘optiping.txt’
‘pngcrush’ -> ‘pngcrush.txt’
‘thunderbird’ -> ‘thunderbird.txt’
‘tmux’ -> ‘tmux.txt’
$ ls -1
chrome_plugins.txt
ffmpeg.txt
firefox-plugins.txt
git.txt
mencoder.txt
nautilus_del_key.txt
optiping.txt
pngcrush.txt
Thunderbird 5 Shortcuts.pdf
thunderbird.txt
tmux.txt
So far so good. But now I realized, I have lot of sub-directories within sub-directories. It has become very painful to CD to every directory and run the script.
How do I make changes in the script so that it is applied recursively. I tried this - it doesn't work.
Code:
$ find . -type f -exec textren {} +
I'm scripting beginner and have written this script after a lot of research


.
I just want to rename files recursively with this script. What do I have to change so that I can achieve that ?
Thank You.