How about:
for f in *; do mv "$f" "$f"_$(wc -l < "$f"); done
For example:
$ wc -l *
10 file1
40 file2
100 file3
$ ls
file1_10 file2_40 file3_100
If you want to keep extensions (if present), use this instead:
for f in *; do
ext="";
[[ $f =~ \. ]] && ext="."${f#*.};
mv "$f" "${f%%.*}"_$(wc -l < "$f")$ext;
done
I wrote a small bash script to do the job.
#!/bin/bash
# Variables
extension='mobi'
report='report.log'
if [ -f $report ];
then
rm -rf $report
fi
echo $'renaming files . . .\n'
for filename in *.$extension
do
temp=$(echo $filename | tr '_' ' ' | tr '%20' ' ' | tr '[]' '()' | tr -s ' ' | sed 's/\.[^.]*$//' )
part1=$(echo $temp | cut -f1 -d-)
part2=$(echo $temp | cut -f2 -d-)
new_filename=$(echo "${part2#?} - ${part1%?}.$extension")
echo $(mv -v "$filename" "$new_filename") | tee -a $report
if [ $? -ne 0 ]; then
echo $'\n\nScript FAILED'
exit 1
fi
done
echo $'\n\nScript SUCCESSFUL'
exit 0
Create a .bsh file inside the directory in which your .mobi files are stored and paste the above code :
Open a Terminal with Ctrl + Alt + T and navigate to the directory in which your script is stored :
cd /path/to/directory/
To change the permissions of the script :
chmod +x <filename>.bsh
To execute the script :
bash <filename>.bsh
If for some reason the mv
fails you will receive an error 'Script FAILED'
, otherwise you'll get 'Script SUCCESSFUL'
.
Explanation
tr '_' ' '
replace underscores with whitespace
tr '%20' ' '
replace %20
with whitespace
tr '[]' '()'
replace square brackets with parentheses
tr -s ' '
replace multiple spaces with one
sed 's/\.[^.]*$//'
extracts only the name of the file without the extension
${string#?}
remove first character of a string
${string%?}
remove last character of a string
mv -v
this will show in the terminal which files are being moved. -v
stands for verbose.
tee -a changelog.log
By default tee
command reads from standard input, and writes to standard output and files. -a
stands for append.
if [ $? -ne 0 ]
checks if the previous command was successful.
report.log
stores the previous and latest name of each file.
Note
The script assumes that the filename contains only one dash -
Best Answer
One way is to use
find
with-exec
, and the+
option. This constructs an argument list, but breaks the list into as many calls as needed to operate on all the files without exceeding the maximum argument list. It is suitable when all arguments will be treated the same. This is the case withrename
, though not withmv
.You may need to install Perl rename:
Then you can use, for example:
Remove
-n
after testing, to actually rename the files.