6

How can I add elements of a list as a prefix plus a "_" to filenames?

filenames:

aaa.gf
bbr.gf
cee.gf

list.txt:

pplo
125ss
35w2

wanted result:

pplo_aaa.gf
125ss_bbr.gf
35w2_cee.gf

All elements are on the same folder. All target files end in .gf. Lines of list.txt should correspond to filenames alphabetically sorted, as shown in the example.

Got stuck on:

for f in *.gf; do mv "$f"  LINE_"$f"; done

Don't know how to make LINE work.

Thanks.

5

How about

mapfile -t list < list.txt

i=0
for f in *.gf; do 
  echo mv "$f" "${list[i++]}_$f"
done

Remove the echo once you are happy that it is doing the right thing.

|improve this answer|||||
5

With POSIX sh syntax:

#! /bin/sh -
for f in *.gf; do
  IFS= read -r line <&3 || break
  mv -i -- "$f" "${line}_$f"
done 3< list.txt

Globbing (here *.gf) sorts the list of files lexically (as per the locale's collation order in modern and POSIX compliant shells).

|improve this answer|||||
0

POSIX-compliant solution would be:

#!/usr/bin/env sh

i=0
for f in *.gf
do
    echo mv "$f"  "$(tail -n+$i list.txt | head -1)"_"$f"
    i=$((i+1))
done

Tested with bash, dash, mksh and yash.

|improve this answer|||||
0

With the paste(1) utility (avoiding slow shell loops, and overall simpler):

# example list of files:
ls > files

paste -d_ list files

If you need to a mv, then things are only slightly more complicated:

paste -d_ list files | paste files - | xargs -n2 echo mv

Remove the echo when you're ready to go.

Since we don't use anything but

The whole thing should be POSIX compliant, sh-compliant, and therefore extremely portable.

But my favorite part is how easy it is to put together on the fly, interactively, piece by piece.

|improve this answer|||||
0

Using GNU Parallel:

parallel mv {1} {2}_{1} ::::+ filenames list.txt

or:

parallel mv {1} {2}_{1} ::: * ::::+ list.txt
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.