0

I have an array with name VERSION that I take from mydir directory and it has parameters(files) as below:

VERSION[0]="TEST01_0.TEST01_1"
VERSION[1]="TEST03_1"
VERSION[2]="TEST02_1.TEST02_2"
VERSION[3]="TEST04_2"
VERSION[4]="TEST02_3" 

And I was trying to rename TEST01_0.TEST01_1 as TEST01_1 and TEST02_1.TEST02_2 as TEST02_2.But I am getting some error as below:

mv: cannot stat `TEST01_0.TEST01_1': No such file or directory
mv: cannot stat `TEST02_1.TEST02_2': No such file or directory

Can you please help me to fix it? Here is my code block:

#!/bin/sh
VERSION=(/mydir/TEST*)
for file in "${VERSION[@]}"
do
    if [[ `echo ${file} | grep -o '_' | wc -l` == 2 ]]; then
    mv "${file}" "${file%.*}";
    fi
done

Thanks

6
  • #! /bin/sh? How are you running the file? Commented Feb 23, 2017 at 9:48
  • I save it as test.sh and copy it to the lab then run the bash test.sh Commented Feb 23, 2017 at 10:23
  • @OscarSayin: Can you run the script after navigating to mydir? Commented Feb 23, 2017 at 10:25
  • You say VERSION has TEST01_0.TEST01_1, TEST03_1, etc., but VERSION=(/mydir/TEST*) will mean it has /mydir/TEST01_0.TEST01_0, /mydir/TEST03_01, etc. Even so, the files should exist. Is this actually what you're running? What does bash -x test.sh output? Commented Feb 23, 2017 at 10:29
  • These files are already in /mydir. I just want to rename the file name which has two '_' characters as their last part of the original names. I mean I want to see my array elemenst like:VERSION[0]=".TEST01_1" VERSION[1]="TEST03_1" VERSION[2]="TEST02_2" VERSION[3]="TEST04_2" VERSION[4]="TEST02_3" Commented Feb 23, 2017 at 10:37

1 Answer 1

1

The best way for this would be to run from inside mydir with bash as below and not relying on any third party utilities like cut or grep

#!/bin/bash

for file in T*
do 
    # Getting the string only containing '_' and if the count matches, 2
    # doing the file rename

    dashes="${file//[^\_]/}"
    if (( "${#dashes}" == 2 ))
    then 
        mv -v "$file" "${file%.*}"
    fi
done
Sign up to request clarification or add additional context in comments.

7 Comments

@OscarSayin: Happy to be of help!
can I ask you more question? How can I rename file from Upgrade.TEST01_0.TEST01_1.sql to Upgrade.TEST01_1.sql. I want to remove TEST01_0 from file name. I have tried like mv -v "${file}" "${file##upgradeDb.*.}" but it didnt work.
Is it always after first two dots from beginning, i.e. skippping Upgrade and TEST01_0
I want to remove from first dot to second dot. I dont want to remove all after first dot
@OscarSayin: It might need a proper regex, can you post it as a new question with your attempt, I will try and quickly answer it
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.