9

I am working on a simple shell script to change a file one.PDF to one.pdf. I have this file stored in a folder called Task1.

My script is in the same directory as Task1. Called Shell1.sh When I run it Task1 becomes Task1.pdf but the file inside one.PDF doesn't change. I need it the other way around but nothing I try seems to work I keep alternating between a syntax error, mv not being able to move because a resource is busy or just renaming the directory.

Can anyone tell me what I'm doing wrong?

#!/bin/bash
#shebang for bourne shell execution
echo "Hello this is task 1"
 #Initial prompt used for testing to see if script ran
#/rename .* .pdf *.pdf // doesnt work

#loop to iterate through each file in current directory and rename
for file in Task1;
do
        mv "$file" "${file%.PDF}.pdf"
done
16

Use globbing to get the filenames:

for file in Task1/*; do mv ...; done

For precision, only match the files ending in .PDF:

for file in Task1/*.PDF; do mv ...; done

More precise, make sure we are dealing with files, not directories:

for file in Task1/*.PDF; do [ -f "$file" ] && mv ...; done

As a side note, your parameter expansion pattern is fine.

| improve this answer | |
  • 1
    @OP re: for and globbing, there seems to be a conceptual misunderstanding. for really only works on a set of strings, separated by the value of the variable $IFS. It does not do any logic (like reading the content of a folder) by itself. That's what Task1/* does, triggering the shell to do the hard work. – Boldewyn Jan 24 '17 at 9:13
  • 1
    applying the first and second lines did the job. But if I add a new file .three.PDF for some reason the script ignores it. I think it's because the dot makes it hidden. But I don't know how to make my loop access it. Any advice? – Callat Jan 24 '17 at 15:02
  • 2
    @KazRodgers Set the dotglob option: shopt -s dotglob – heemayl Jan 24 '17 at 15:21
  • 1
    I see. shopt lets you tweak the built in behavior -s is an option to affect the built in names. and dot glob contains all the strings that start with a dot. Geez I probably would have never found that on my own. Thanks a bunch! – Callat Jan 24 '17 at 15:35
4

Aside from basic shell commands, on most Lunux distributions there is a nice tool rename that can do the job of renaming multiple files in single command:

rename 's/PDF/pdf/' Task1/*

Here is a nice article about it: Rename – A Command Line Tool For Renaming Multiple Files in Linux.

| improve this answer | |
  • Careful, some distributions have a rename that is a completely different command. – wingedsubmariner Jan 24 '17 at 20:19
1

If your distribution's rename is the C command from util-linux (e.g. Arch Linux):

rename PDF pdf Task1/*PDF

This will work unless your PDF files contain the string "PDF" somewhere other than the end, e.g. example_PDF_file.PDF.

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.