0

I have a bash script in which I'm trying to list jpg files in order of modification date, followed by renaming them in numerical order (0.jpg, 1.jpg, 2.jpg, etc...) using xargs. This needs to occur in multiple directories. Here is the code:

ls -1rt "/media/171/" | xargs rename  's/^[^\.]*(\..*)?$/our $i; sprintf("%01d$1", $i++)/e'
ls -1rt "/media/193/" | xargs rename  's/^[^\.]*(\..*)?$/our $i; sprintf("%01d$1", $i++)/e'
ls -1rt "/media/211/" | xargs rename  's/^[^\.]*(\..*)?$/our $i; sprintf("%01d$1", $i++)/e'

The problem is that when I execute the script, the files are listing ok, but xargs throws an error that can't find the file specified. It only works when I run the command from within each directory. I realize you can't "cd /" within a bash script, and the problem seems to be that xargs isn't being passed the full file path. How can I pass the full file path on to the xargs command?

  • Use the find command e.g. find . -type f -print0 | xargs -0 /bin/ls -ltr – Kyle Banerjee Sep 15 '18 at 15:27
0

The only error about files that xargs may throw is that it didn't find the executable, rename in this case. Everything else about files has to come from the program that xargs runs.

A shell script can use the cd command. But in this case, the script has no way to know what directory it should use.

You may want to try

( cd "/media/171/" && ls -1rt | xargs rename  's/^[^\.]*(\..*)?$/our $i; sprintf("%01d$1", $i++)/e' )
  • Thanks, but this didn't work for me. I tried a few other things but could not get this to work properly in bash. I've had to move on to some other things but may be able to come back to this in the future. – Liam Sep 26 '18 at 1:17
  • Sorry, had a typo, it must be &&, not &. – RalfFriedl Sep 26 '18 at 4:57

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.