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?
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?
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")"
var=$(echo x;echo y); echo "$var"
it prints x
and y
on differnt lines.
– Lucas
Apr 17 '16 at 21:27
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
ls | sort
and try tomv
the file you want by hand if you only need to do this once. – Lucas Apr 17 '16 at 20:41\``). So
ls /list | tail -n 1is the file you want to move? Why not just use
mv` to move it? – Lucas Apr 17 '16 at 20:45mv /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