Hi I an FTP folder called Input where I get sent files which look something like this:

"Guide to Iceland _ Chen-ping Wang itinerary T-987654987.pdf"
"Guide to Iceland _ T-123654875 Chen-ping Wang itinerary.pdf"

Basicly the description of the file can be different but it always includes "T-" and some numbers.

I need to create a bash script that copies the file to the folder ../Output and renames the file so the "T-" and the numbers comes first, and then rest of the filename. Example: "T-123654875 - Guide to Iceland _ Chen-ping Wang itinerary.pdf"

I intended to use Grep to get the name right. Searching for (.+)(T-\d+) and replacing it with $2 - $1

But I can't get it to work right.

  • 1
    Does your system have the perl-based rename / prename command? – steeldriver Jan 11 '19 at 1:02
  • I am running this on Macintosh and intended to use the move mv command to rename it. – Þorgeir Valur Ellertsson Jan 11 '19 at 1:28
  • 1
    What do your current efforts look like? – tink Jan 11 '19 at 1:50

grep alone and replace to me doesn't look like a usable combo. How do you feel about sed?

$ ls *pdf
Guide to Iceland _ Chen-ping Wang itinerary T-987654987.pdf
Guide to Iceland _ T-123654875 Chen-ping Wang itinerary.pdf

And then a little for loop in bash:

$ for i in *pdf; do mv "$i" "$( echo $i |  sed -r  's/^(.*)(T-[0-9]{9})(.+)$/\2 - \1\3/'  )"; done

This iterates over all PDFs in the current directory; stores their name in $i for every iteration, echos the content through sed (and uses its output as the target of the mv). sed breaks up the file-name in three parts and rearranges these. I recommend replacing mv with echo mv for testing :)

Which gives us:

$ ls *pdf
T-123654875 - Guide to Iceland _  Chen-ping Wang itinerary.pdf
T-987654987 - Guide to Iceland _ Chen-ping Wang itinerary .pdf
| improve this answer | |
  • Thank you @tink sed is deffenetly the tool I should be using. There where one fault with the code to have it run in bash in my case sed use "-E" in stead of "-r" for regular expression. $ for i in *pdf; do mv "$i" "$( echo $i | sed -E 's/^(.*)(T-[0-9]{9})(.+)$/\2 - \1\3/' )"; done But I need help making changes to the code. I don't need to check if it is PDF and I use an app to run the script and it Use $1 to refer to the file being processed. Can you help me make the modification so it works. – Þorgeir Valur Ellertsson Jan 13 '19 at 1:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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