인생에 뜻을 세우는데 있어 늦은 때라곤 없다

WEB/Server

쉘 스크립트를 사용하여 여러 파일의 확장자를 변경하십시오

projin 2019. 8. 30. 15:13

Unix / Linux 환경에서는 mv파일을 이동하는 명령이거나 파일 확장자를 변경하는 데 사용할 수 있습니다. 그러나 단일 파일에서만 작동하며 다른 문자를 사용합니다. 여기에는 디렉토리에서 여러 파일의 확장자를 변경하는 데 사용할 수있는 간단한 스크립트가 제공됩니다.

 

1. 먼저 Shell 파일을 만듭니다.


#!/bin/sh

#Save file as multimove.sh

IFS=$'
'

if [ -z "$1" ] || [ -z "$2" ]
then
  echo "Usage: multimove oldExtension newExtension"
  exit -1
fi
# Loop through all the files in the current directory
# having oldExtension and change it to newExtension
for oldFile in $(ls -1 *.${1})
do
# get the filename by stripping off the oldExtension
  filename=`basename "${oldFile}" .${1}`
# determine the new filename by adding the newExtension
# to the filename
  newFile="${filename}.${2}"
# tell the user what is happening
  echo "Changing Extension "$oldFile" --> "$newFile" ."
mv "$oldFile" "$newFile"
done

 

2. 사용법 : multimove.sh doc txt (모든 .doc 파일을 .txt 파일로 변경)


$ ls
abc.txt        hi.doc        journaldev.doc    multimove.sh
$ ./multimove.sh doc txt
Changing Extension "hi.doc" --> "hi.txt" .
Changing Extension "journaldev.doc" --> "journaldev.txt" .
$ ls
abc.txt        hi.txt        journaldev.txt    multimove.sh
$ ./multimove.sh txt doc
Changing Extension "abc.txt" --> "abc.doc" .
Changing Extension "hi.txt" --> "hi.doc" .
Changing Extension "journaldev.txt" --> "journaldev.doc" .
$ ls
abc.doc        hi.doc        journaldev.doc    multimove.sh
$
LIST