Score:0

Move images to a seperate directory after reading their names from a file in bash

us flag

I'm trying to read images' names from a file text which is rgb_train_ids.txt, and then I will move the images after reading their names to a new folder which is Train.

#!/bin/bash

for file in $(cat rgb_train_ids.txt); do 
     mv "$file.png" "Train"; 
done

When I execute the above bash script, it only moves the second image img_2 and shows this:

mv: cannot stat 'img_1'$'\r''.png': No such file or directory

I've noticed that, it always moves the last line in the file text.
I don't know where the problem is, could you help me?

enter image description here

Score:1
hr flag

The $'\r' indicates that the lines in your rgb_train_ids.txt have DOS-style line endings, consisting of the 2-character sequence CRLF. Linux expects files to use just LF. You can convert the file using the dos2unix utility, or strip the CR characters off using tr or sed for example.

As well, looping over lines using for file in $(cat rgb_train_ids.txt) is a bad practice - it will fail if the lines contain whitespace or other shell-special characters. You should consider using a while loop instead:

while IFS= read -r file; do
  mv "$file.png" Train/
done < <(tr -d '\r' < rgb_train_ids.txt)

The trailing / on Train/ is a safety measure that will cause the mv command to error out if directory Train doesn't exist - instead of unintentionally renaming each file. Alternatively you could use mv -t Train "$file.png" to make it explicit that Train is the target directory.

See also

You could also consider using xargs rather than a shell loop:

tr -d '\r' < rgb_train_ids.txt | xargs -d '\n' mv -t Train
Abanoub Asaad avatar
us flag
Thank you so much, I really appreciate your time and efforts!
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.