4

I want to rename .gz files according to names in separate txt-file. I have a map with .gz files with the names:

trooper10.gz
trooper11.gz 
trooper12.gz
etc.

and I have a separate txt-file with the wanted name(s) in in the first column and the .gz-names in the other column (tab-separated).

B25    trooper10
C76    trooper11
A87_2    trooper12

So the files should be renamed like this

B25.gz
C76.gz
A87_2.gz

I tried

for i in *.gz; do
line=$(grep -x -m 1 -- "${i}" /path_to_txtfile/list_names.txt)

But im not sure how to grep the corresponding column in the txt-file. Since there is many gz-files I want to ask if there is any way to this?

2 Answers 2

8

Yes, you just start by reading the file instead of getting the gz files from the file system:

while IFS=$'\t' read -r newName oldName; do
    mv -- "$oldName".gz "$newName.gz"
done < names_file
3
  • When I tried this, I receive the following error: mv: cannot stat 'trooper10'$'\r''.gz': No such file or directory
    – Yoshi
    Mar 1 at 10:20
  • 4
    @Yoshi that's because you seem to be using Windows and not Linux? Your file is a Windows text file with Windows line endings. Fix the file with dos2unix names_file or sed -i 's/\r//' names_file and try again.
    – terdon
    Mar 1 at 10:24
  • The \r suggests that your names_file came from a windows machine. try converting it with fromdos (or tr -d $'\r' if you don't have fromdos or similar)
    – cas
    Mar 1 at 10:25
5

Could that not just be:

<list_names.txt awk -F'\t' '{printf "%s.gz\0%s.gz\0", $2, $1}' | xargs -r0n2 mv --

Or more efficiently:

perl -F'\t' -lae 'rename "$F[1].gz", $"F[0].gz" or warn "$F[1].gz: $!\n"' list_names.txt
3
  • No need -a with -F (implicit) Mar 1 at 10:49
  • Thanks @Gilles, I wasn't aware that. May be better to keep it though to make it clear that the awk mode is being used and would remain in use even if we removed the -F to revert to using the default separator. I'm undecided. Mar 1 at 11:16
  • You can choose -F or -a, both should works. But using both at the same time is redundant. To be close like awk, you can keep -F and remove -a that is not related to awk unlike -F Mar 1 at 11:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .