I am trying to write a script which will take my file and rename pt-1 to pt2 for eg. testfile_pt-1_date.ts at the moment the script will correctly rename to file and copy it to the specified folder correctly.

The problem I have is if there is a file eg. testfile_pt_date.ts, the file is not being renamed but is being copied which is not what I want, I want the file to be ignored, I am not sure why the for do loop is accepting a file with pt in it, anyone know where I have gone wrong.

#! /bin/bash

for file in *_pt-1_*.ts
echo "$1"    
a="$(echo $1 | sed s/_pt-1_/_pt2_/)"
cp "$1" "$HOME/SGTV/${a##*/}"
echo "$a"
  • 4
    You're doing file=$1, but then $file is overriden as you're doing for file in .... And in the loop, you're not using $file, but $1 instead. – Stéphane Chazelas Aug 21 '17 at 16:33
  • 3
    You're also using cp and not mv, and if your complaint is that it is copying the file, it's because you're explicitly telling it to. – DopeGhoti Aug 21 '17 at 16:35
  • Yes cp is fine thats what I wanted, what would I use in place of file then in for file in .....? I guess all my variable are a bit mixed up. thanks – JohnDOw Aug 21 '17 at 17:45
  • a="${file/_pt-1_/_pt2_}" – Cyrus Aug 21 '17 at 19:43

Instead of a loop, I would suggest you to use the dedicated rename tool. It's easier to read, faster to write and avoid confusion.

rename 's/_pt-1_/_pt2_/' *_pt-1_*.ts

Warning: rename is a mess on most distributions. If you're using Debian or a derivative, make sure the rename package is installed (not just the rename binary).

  • Thanks, Yes the rename solution works very nicely from a command line. My problem is I need the solution needs wrapped into a bash file as it is called via an external program and is why I am left to try and incorporate the external filename variable $1 into the script. – JohnDOw Aug 21 '17 at 21:55
  • Well you can use $1 as well: rename 's/_pt-1_/_pt2_/' $1 – abitmol Aug 22 '17 at 8:39

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.