Max_IT
Max_IT

Reputation: 626

renaming multiple files adding a counter in bash

I had a look around other topics, but I am still doing it wrong. I am a total beginner in bash, sorry if I'm asking something already asked in other topics. My purpose: change the name of multiple files adding numbers to them. E.g.: my files: filexx.txt, fileyy.txt, filezz.txt The result I want: test_name_1_filexx.txt, test_name_2_fileyy.txt, test_name_3_filezz.txt

What I have written so far:

#!/bin/bash
COUNTER=1
MYSTRING=test_name_
for i in *.txt
do
 mv "$i" "$(printf $MYSTRING $COUNTER '_' $i)"
 COUNTER="$COUNTER"+1
done

The above basically leaves only the last file in the directory, and it names it "test_name_" Thanks for your help :)

Upvotes: 0

Views: 61

Answers (2)

Cyrus
Cyrus

Reputation: 88583

With GNU bash:

MYSTRING="test_name_"
c=1; for i in *.txt; do echo mv -v "$i" "${MYSTRING}$((c++))_$i"; done

If output looks okay, remove echo.

Upvotes: 1

that other guy
that other guy

Reputation: 123410

Here's an easier way to reproduce your problem:

$ printf foo bar baz
foo

The "bar" and "baz" are ignored. This is because printf takes one message with format specifiers, and a number of variables to substitute:

$ printf "%s, %s and %s" foo bar baz
foo, bar and baz

Since it looks like you just want to concatenate variables, there's no point in using printf at all:

#!/bin/bash
counter=1
mystring=test_name_
for i in *.txt
do
 mv "$i" "${mystring}${counter}_${i}"
 counter=$((counter+1))
done

Upvotes: 4

Related Questions