-1

I want my script to read from a listofNewNames and then save a new file under a new name which will be the first three letters of the file name plus a counter adding one for every file beginning with the same three letters.

Suppose these are my old and new file names-

listofFileNames: A77 A77 A77 A78 A78

listofNewNames: A7701 A7702 A7703 A7801 A7802 (prospective, listofNewNames is not intended to be saved)

COUNTER=0
for i in listofFileNames; do
while [$COUNTER -lt 5]
let "COUNTER=COUNTER+01"
done
newName=${oldfilename}${COUNTER}.L2_LAC_OC
done

This is so far what I have but whenever the letters change the counter has to re-start to 0 so the lenght of the file names is never 5. It is, for example, 3 and then 2, depending on the amount of files.

I hope I had make myself clear. Thanks in advance.

  • What would the 101st file be named? – DopeGhoti Dec 1 '17 at 20:39
  • Please mark an answer as solution or tell us what you need. – FaxMax Dec 1 '17 at 21:14
1
last_name=""
listofFileNames=(A77 A77 A77 A78 A78)

for name in "${listofFileNames[@]}"; do
        test "$name" != "$last_name" && COUNTER=1
        last_name="$name"
        printf "%s%02d\n" "${name}" "${COUNTER}"
        ((COUNTER++))
done
1

See this:

ListOfFiles=("A77" "A77" "A77" "A78" "A78")
for oldfile in "${ListOfFiles[@]}"; do 
    COUNT=1; 
    while [[ -f "$(printf "%s%02d" ${oldfile} ${COUNT})" ]]; do 
        COUNT=$(($COUNT + 1)) 
    done 
    echo "NewName: $(printf "%s%02d" ${oldfile} ${COUNT})"
    touch "$(printf "%s%02d" ${oldfile} ${COUNT})"
done

at the moment the script will give you Filenames like

NewName: A7701
NewName: A7702
NewName: A7703
NewName: A7801
NewName: A7802

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.