Komut dosyası, birden çok durumu kapsar: tek nokta ve uzantı (dosya.txt), birden çok nokta ve uzantı (dosya.1.txt), ardışık noktalar (dosya..foobar.txt) ve dosya adındaki noktalar (dosya. Veya dosya..).
Senaryo
#!/bin/bash
# Author: Serg Kolo
# Date: June 25,2015
# Description: script to rename files to file_numlines
# written for http://askubuntu.com/q/640430/295286
# Where are the files ?
WORKINGDIR=/home/xieerqi/substitutions
# Where do you want them to go ?
OUTPUTDIR=/home/xieerqi/substitutions/output
for file in $WORKINGDIR/* ;do
FLAG=0
EXT=$(printf "%s" "$file" | awk -F'.' '{printf "%s",$NF }' ) # extension, last field of dot-separated string
# EXT="${file##*.}" # Helio's advice is to use parameter expansion, but I dont know how to use it
if [ -z $EXT ]; then # we have a dot at the end case file. or something
# so we gotta change extension and filename
EXT=""
FILENAME=$(printf "%s" "$file" | awk -F '/' '{ print $NF}' )
# set flag for deciding how to rename
FLAG=1
else
FILENAME=$( printf "%s" "$file" | awk -F '/' -v var=$EXT '{gsub("."var,"");print $NF}' ) # filename, without path, lst in
fi
NUMLINES=$(wc -l "$file" | awk '{print $1}') # line count
if [ $FLAG -eq 0 ];then
echo "$file" renamed as "$OUTPUTDIR"/"$FILENAME"_"$NUMLINES"."$EXT"
# cp "$file" "$OUTPUTDIR"/"$FILENAME"_"$NUMLINES"."$EXT" # uncomment when necessary
else
echo "$file" renamed as "$OUTPUTDIR"/"$FILENAME"_"$NUMLINES""$EXT"
# cp "$file" "$OUTPUTDIR"/"$FILENAME"_"$NUMLINES""$EXT" # uncomment when necessary
fi
#printf "\n"
done
Komut dosyası iş başında
$./renamer.sh
/home/xieerqi/substitutions/file. renamed as /home/xieerqi/substitutions/output/file._0
/home/xieerqi/substitutions/file.. renamed as /home/xieerqi/substitutions/output/file.._0
/home/xieerqi/substitutions/file.1.jpg renamed as /home/xieerqi/substitutions/output/file.1_3.jpg
/home/xieerqi/substitutions/file.1.test.jpg renamed as /home/xieerqi/substitutions/output/file.1.test_3.jpg
/home/xieerqi/substitutions/file.1.test.txt renamed as /home/xieerqi/substitutions/output/file.1.test_2.txt
/home/xieerqi/substitutions/file.1.txt renamed as /home/xieerqi/substitutions/output/file.1_2.txt
/home/xieerqi/substitutions/file.2.jpg renamed as /home/xieerqi/substitutions/output/file.2_3.jpg
/home/xieerqi/substitutions/file.2.test.jpg renamed as /home/xieerqi/substitutions/output/file.2.test_3.jpg
/home/xieerqi/substitutions/file.2.test.txt renamed as /home/xieerqi/substitutions/output/file.2.test_2.txt
/home/xieerqi/substitutions/file.2.txt renamed as /home/xieerqi/substitutions/output/file.2_2.txt
/home/xieerqi/substitutions/foo..bar.txt renamed as /home/xieerqi/substitutions/output/foo..bar_4.txt
Dosyada satır olmadığını unutmayın. ve dosya .., dolayısıyla satır sayısı 0
Komut dosyasını ve önerilen düzenlemeleri gözden geçirdikleri için terdon ve Helio'ya özel teşekkürler