0

So I have a list of files that have numbers similar to the example below:

/list/CAP_0045.dat
/list/CAP_0044.dat
/list/CAP_0046.dat

I want to rename the file with the largest number to add a prefix to it. How do I do this?

Lucas
  • 2,845
  • Please tell us what you tried so far. If you haven't tried anything you are just asking other people to do the thinking and work for you. You can have a look at ls | sort and try to mv the file you want by hand if you only need to do this once. – Lucas Apr 17 '16 at 20:41
  • I have tried a bunch of things with the mv command. I can certainly get the file list to be printed out with the file I want to rename at the top ls -1r /list and make the move manually. The problem is this is for a script that is creating that is executing a command that is creating these new file names. – user166242 Apr 17 '16 at 20:43
  • Please format code with backticks (\``). Sols /list | tail -n 1is the file you want to move? Why not just usemv` to move it? – Lucas Apr 17 '16 at 20:45
  • Sorry I am a noob. I am looking for a command similar to this mv /list/CAP_*.dat /list/SatCAP_*.dat where CAP_*.dat is the largest numbered file and the new file has the same number in it – user166242 Apr 17 '16 at 20:49

1 Answers1

0

You can use command substitution for this (read man sh and look for it).

If ls /list | tail -n 1 prints the correct file you can do this:

file=$(ls /list | tail -n 1)
mv "/list/$file" "/list/PREFIX$file"

EDIT: As pointed out by @Wildcard this can fail if the file names contain newlines.

A solution that should work even with newlines in file names uses find -print0 and {sort,head,tail} -z (seems not all versions support the -z/--zero-terminated option, GNU does):

file=$(find /list -print0 | sort -z | tail -n 1 -z)
mv "$file" "$(dirname "$file")/PREFIX$(basename "$file")"
Lucas
  • 2,845
  • Thank you so much for your help. it would have taken me 4 hours to figure that out. – user166242 Apr 17 '16 at 21:03
  • 1
    @user166242, be aware that this won't handle correctly a filename that contains newlines. Not generally something to worry about on your own computer—I don't think anyone other than a malicious user would put newlines in a filename—but it's still worth keeping in mind. – Wildcard Apr 17 '16 at 21:11
  • @Wildcard how does this create problems with newlines? If I do var=$(echo x;echo y); echo "$var" it prints x and y on differnt lines. – Lucas Apr 17 '16 at 21:27
  • 1
    Try touch "$(echo CAP; echo _099.dat)" in an empty dir and then ls -1 | tail -n 1 and you will see half a filename printed. Such a filename would break your code. As I said, for personal use it may be fine, but it's not completely robust. Also see Why not parse ls? – Wildcard Apr 17 '16 at 21:32