philipovic
philipovic

Reputation: 59

Bash rename multiple files according to line in another file

I would like to rename multiple files according to the name specified in another file. For example, I have a file called names.txt, containing:

Name1 Newname1
Name2 Newname2
Name3 Newname3

etc

In this names.txt file the names are not numbered. However, the name in column 1 and column 2 are linked together. I can imaging it should be possible to loop through the file to extract both names and use it in the mv function somehow. Thanks!

Upvotes: 1

Views: 1429

Answers (2)

soumyaranjan
soumyaranjan

Reputation: 101

This will work even if you have space :

SAVE_IFS=$IFS
IFS=$(echo -en "\n\b")
for row in `cat names.txt`
do
    echo $row
    cur_name=`echo $row | awk -F " " '{print $1}'`
    new_name=`echo $row | awk -F " " '{print $2}'`
    echo "mv $cur_name $new_name"
done
IFS=$SAVE_IFS

Upvotes: 0

Thomas Erker
Thomas Erker

Reputation: 348

Assuming none of the names in names.txt contains whitespace, you can use this:

while read a b; do mv "$a" "$b"; done < names.txt

Upvotes: 2

Related Questions