0

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

file=$1
for file in *_pt-1_*.ts
do
echo "$1"    
a="$(echo $1 | sed s/_pt-1_/_pt2_/)"
cp "$1" "$HOME/SGTV/${a##*/}"
echo "$a"
done
4
  • 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. Commented Aug 21, 2017 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
    Commented Aug 21, 2017 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
    Commented Aug 21, 2017 at 17:45
  • a="${file/_pt-1_/_pt2_}"
    – Cyrus
    Commented Aug 21, 2017 at 19:43

1 Answer 1

0

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).

2
  • 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
    Commented Aug 21, 2017 at 21:55
  • Well you can use $1 as well: rename 's/_pt-1_/_pt2_/' $1
    – abitmol
    Commented Aug 22, 2017 at 8:39

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.