Looks like no one’s replied in a while. To start the conversation again, simply ask a new question.

Script to rename txt files based on text contents in file

Hi Everyone,

I'm trying to get a script that will rename txt files based on a specific word in each file. I have multiple files and somewhere within each of them is a file number in the following format “ABC_###_###_###”, e.g. ABC_101_102_103. I need a script that will find this file number within each file and rename each file as such.

I came across the following thread (https://discussions.apple.com/thread/4870016) which has an answer from twtwtw that gets me fairly close by telling it to rename the file to a certain paragraph in the file, but there is other text on the same line as the file number so it doesn’t quite work, and the file number is not always on the same line. I think I need a script that will search for that letter/number combination, because all the file numbers are in the same format (ABC_###_###_###).

Can anyone help with this? I don’t have much knowledge of script.

Thank you!

MacBook Pro, OS X Yosemite (10.10.3)

Posted on May 29, 2015 1:41 PM

Reply
Question marked as Best reply

Posted on May 29, 2015 1:50 PM

Try using:


tell application "Finder"

repeat with this_file in (get files of (choose folder))

set the_text to read (this_file as alias)

set the_offset to offset of "ABC_" in the_text

if the_offset is not 0 then

set name of this_file to items the_offset thru (the_offset + 14) of the_text as string

end if

end repeat

end tell


(128046)

5 replies
Question marked as Best reply

May 29, 2015 1:50 PM in response to leannamiiso

Try using:


tell application "Finder"

repeat with this_file in (get files of (choose folder))

set the_text to read (this_file as alias)

set the_offset to offset of "ABC_" in the_text

if the_offset is not 0 then

set name of this_file to items the_offset thru (the_offset + 14) of the_text as string

end if

end repeat

end tell


(128046)

May 30, 2015 5:41 AM in response to leannamiiso

Another alternative is a bash script that can be wrapped in an Automator Action:


User uploaded file


The Run Shell Script Action is:


for f in "$@"
do
  n=$( grep -E -o -m1 '[A-Z]{3}_[0-9]{3}_[0-9]{3}_[0-9]{3}' "$f" )
  if [ $? -eq 0 ] ; then
       p=${f%/*}
       mv "$f" "$p/$n"
  fi
done


Note: If the file already exists (i.e. two different files containing the file number ABC_101_102_103, the file will be overwritten)

Script to rename txt files based on text contents in file

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple ID.