Processing files one by one using data from pipe

Hi guys, I receive a list from pipe (with fixed number of lines) like this:

name1
name2
name3

And in my ./ folder I have three files:

01-oldname.test
02-someoldname.test
03-evenoldername.test

How to rename files one by one using while read?
Desired result:

01-name1.test
02-name2.test
03-name3.test

I guess construction should look like this:

cat ../names.txt | while read -r line; do mv

One approach is to load names into an indexed array and then use another loop to rename the files using the array:-

#!/bin/ksh

# Load names into an indexed array
c=1
while read file
do
        A_fname[$c]="$file"
        (( ++c ))
done < names.txt

# Rename *.test files using array value
c=1
for file in *.test
do
        if [ ! -z ${A_fname[$c]} ]
        then
                print "mv ${file} ${file%%-*}-${A_fname[$c]}.test"
                (( ++c ))
        fi
done

Remove the highlighted print and rerun if the output looks good.

1 Like

Try also

ls *.test | while read FN && read NFN <&3; do echo mv $FN ${FN%-*}-$NFN.${FN#*.}; done 3<names.txt
mv 01-oldname.test 01-name1.test
mv 02-someoldname.test 02-name2.test
mv 03-evenoldername.test 03-name3.test

remove echo if happy with result.

1 Like

Another variation:

for i in *.test; do
  read new || break
  mv "$i" "${i%%-*}-${new}.${i##*.}"
done <names.txt
2 Likes