ผู้เขียน หัวข้อ: Replace all occurences of spaces in filenames with an underscore character  (อ่าน 1257 ครั้ง)

admin

  • Administrator
  • Newbie
  • *****
  • กระทู้: 22
    • ดูรายละเอียด
Replace all occurences of spaces in filenames with an underscore character
« เมื่อ: กุมภาพันธ์ 17, 2015, 01:17:48 PM »
Create file : no_spacebar.sh
vim no_spacebar.sh 

input line below :

โค๊ด: [Select]
#!/bin/sh
#
# (Hopefully) replace all occurences of spaces in filenames with an underscore character
#
# Expected Usage: killspc [regexp]
# regexp represents location and types of files to rename i.e $HOME/downloads/*
#

TOTAL_RENAMED=0
for NXT_FILE in "$@" ; do
        case "$NXT_FILE" in *' '*)
        OLD_NAME="$NXT_FILE"
        NEW_NAME=`echo "$OLD_NAME" | tr ' ' '_'`
        echo -e "Renaming file `basename "$OLD_NAME"` to `basename $NEW_NAME`...\c"
        OLDIFS="$IFS"
        IFS=:
        mv "$OLD_NAME" "$NEW_NAME"
        IFS="$OLDIFS"
        if [ $? -eq 0 ]; then
                echo "ok"
                TOTAL_RENAMED=$(( $TOTAL_RENAMED +1 ))
        else
                echo "failed"
        fi
        ;;
        esac
done

change permission file to 755
chmod 755 no_spacebar.sh 

and copy file no_spacebar.sh   to destination folder

Before :
ls -la
total 12

-rwx------ 1 root root  657 Mar 26 12:53 no_spacebar.sh
-rw-r--r-- 1 root root    0 Mar 26 12:50 test2 test
-rw-r--r-- 1 root root    0 Mar 26 12:50 test3 test
-rw-r--r-- 1 root root    0 Mar 26 12:50 test4 test
-rw-r--r-- 1 root root    0 Mar 26 12:50 test5 test
-rw-r--r-- 1 root root    0 Mar 26 12:49 test test


./no_spacebar.sh test*

after :

ls -al
โค๊ด: [Select]
-rwx------ 1 root root  658 Mar 26 12:56 no_spacebar.sh
-rw-r--r-- 1 root root    0 Mar 26 12:50 test2_test
-rw-r--r-- 1 root root    0 Mar 26 12:50 test3_test
-rw-r--r-- 1 root root    0 Mar 26 12:50 test4_test
-rw-r--r-- 1 root root    0 Mar 26 12:50 test5_test
-rw-r--r-- 1 root root    0 Mar 26 12:49 test_test


How to use : Copy file no_spacebar.sh to destination folder and run

 
« แก้ไขครั้งสุดท้าย: กุมภาพันธ์ 17, 2015, 01:20:35 PM โดย admin »