Home > Mobile >  Is there a way to add a suffix to files where the suffix comes from a list in a text file?
Is there a way to add a suffix to files where the suffix comes from a list in a text file?

Time:09-13

So currently the searches are coming up with a single word renaming solution, where you define the (static) suffix within the code. I need to rename based on a text based filelist and so -

I have a list of files in /home/linux/test/ :

1000.ext
1001.ext
1002.ext
1003.ext
1004.ext

Then I have a txt file (labels.txt) containing the labels I want to use:

Alpha
Beta
Charlie
Delta
Echo

I want to rename the files to look like (example1):

1000 - Alpha.ext
1001 - Beta.ext
1002 - Charlie.ext
1003 - Delta.ext
1004 - Echo.ext

How would you a script which renames all the files in /home/linux/test/ to the list in example1?

CodePudding user response:

Use paste to loop through the two lists in parallel. Split the filenames into the prefix and extension, then combine everything to make the new filenames.

dir=/home/linux/test
for file in "$dir"/*.ext
do
    read -r label
    prefix=${file%.*} # remove everything from last .
    ext=${file##*.}   # remove everything before last .
    mv "$file" "$prefix - $label.$ext"
done < labels.txt

CodePudding user response:

I originally partly got the request wrong, although this step is still useful, because it gives you the filenames you need.

#!/bin/sh

count=1000
cp labels.txt stack

cat > ed1 <<EOF
1p
q
EOF

cat > ed2 <<EOF
1d
wq
EOF

next () {
[ -s stack ] && main
}

main () {
line="$(ed -s stack < ed1)"
echo "${count} - ${line}.ext" >> newfile
ed -s stack < ed2
count=$(($count 1))
next
}

next

Now we just need to move the files:-

cp newfile stack
for i in *.ext
do
newname="$(ed -s stack < ed1)"
mv -v "${i}" "${newname}"
ed -s stack < ed2
done

rm -v ./ed1
rm -v ./ed2
rm -v ./stack
rm -v ./newfile
  •  Tags:  
  • bash
  • Related