Reputation: 109
Hello everybody i'd like to know how to rename a file using part of a name stored in a variable. To be more clear i'll show you an example. Let's say i have to loop through all the files called test_*.txt so test_1.txt, test_2.txt ... test_45.txt and so on. At a point in the loop i need to rename a file test-name.txt in test-name1.txt, test-name2.txt according to the number in the test_1.txt file
for test in test_*.txt
do
'rename test-name.txt to test-name(number in test).txt'
done
Upvotes: 0
Views: 75
Reputation: 31
You can also use pattern matching in bash:
[[ $file =~ test_(.*).txt ]];
mv test_name.txt test_name${BASH_REMATCH[1]}.txt
Upvotes: 0
Reputation: 36076
This should work:
for tst in test_*.txt
do
nr=${tst#test_} # Delete 'test_' from beginning of file name in tst
nr=${nr%.txt} # Delete '.txt' from end of file name in tst
mv test_name.txt test_name_${nr}.txt
done
Upvotes: 2