Kịch bản dưới đây bao gồm nhiều trường hợp: dấu chấm đơn và phần mở rộng (file.txt), nhiều dấu chấm và phần mở rộng (file.1.txt), dấu chấm liên tiếp (file..foobar.txt) và dấu chấm trong tên tệp (tệp. Hoặc tập tin..).
Kịch bản
#!/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
Kịch bản hành động
$./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
Lưu ý rằng không có dòng trong tập tin. và tệp .., do đó số dòng là 0
Đặc biệt cảm ơn terdon và Helio đã xem xét kịch bản và đề xuất chỉnh sửa