Reputation: 707
There is a single file in a folder which has date and time appended to it. I would like to rename it to something else so that I can access it easily. I know the starting word of this file name. Is they there a way I can rename this (using wildcard or something)? . Can't use Tab since I am trying to write a script to automate something.
Also, I would like to access the lexicographical last element and rename it if there are multiple files.
Upvotes: 0
Views: 92
Reputation: 653
You can use rename with a regexp. The syntax is:
Usage: rename [-v] [-n] [-f] perlexpr [filenames]
So, given the following files:
coda@pong:/tmp/kk$ ls -l
total 0
-rw-rw-r-- 1 coda coda 0 Jun 10 13:28 aaaa-2016-01-01.txt
-rw-rw-r-- 1 coda coda 0 Jun 10 13:28 aaaa-2016-01-02.txt
-rw-rw-r-- 1 coda coda 0 Jun 10 13:28 aaaa-2016-01-03.txt
-rw-rw-r-- 1 coda coda 0 Jun 10 13:28 aaaa-2016-01-04.txt
You can rename them this way:
coda@pong:/tmp/kk$ rename -v 's/aaaa/xxxx/' *.txt
aaaa-2016-01-01.txt renamed as xxxx-2016-01-01.txt
aaaa-2016-01-02.txt renamed as xxxx-2016-01-02.txt
aaaa-2016-01-03.txt renamed as xxxx-2016-01-03.txt
aaaa-2016-01-04.txt renamed as xxxx-2016-01-04.txt
If you want to keep track of the lexicographical last element, I would use something like this in the script:
ln -sf `ls | tail -n1` latest
Since ls sorts by name by default, you will always have a link to your lexicographical last element:
coda@pong:/tmp/kk$ ls -lrt
total 0
-rw-rw-r-- 1 coda coda 0 Jun 10 13:28 xxxx-2016-01-01.txt
-rw-rw-r-- 1 coda coda 0 Jun 10 13:28 xxxx-2016-01-02.txt
-rw-rw-r-- 1 coda coda 0 Jun 10 13:28 xxxx-2016-01-03.txt
-rw-rw-r-- 1 coda coda 0 Jun 10 13:28 xxxx-2016-01-04.txt
lrwxrwxrwx 1 coda coda 19 Jun 10 13:59 latest -> xxxx-2016-01-04.txt
Upvotes: 1
Reputation: 47099
You want to find the last changed file in a directory? Which matches a pattern?
find . -maxdepth 1 -mindepth 1 -type f -name "prefix*" \
-printf "%TY%Tm%TdTH%TM %p\n" | sort -nr | read -r _ file
printf "%s" "$file"
Assuming no filename contains newlines. And that you actually just want to get the last changed file in a directory.
Alternative you can sort do something like this:
find . -maxdepth 1 -mindepth 1 -type f -name "prefix*" | sort -nr -t- -k2
Which will sort files like this:
prefix-2016-05-05
prefix-2016-06-05
prefix-2016-04-08
To
prefix-2016-06-05
prefix-2016-05-05
prefix-2016-04-08
Upvotes: 1
Reputation: 10063
Assuming the name of the file is bob_2016-06-10_06:00:00.txt
you could do this:
mv *_20[0-9][0-9]-[01][0-9]-[0-3][0-9]_[0-2][0-9]:[0-5][0-9]:[0-5][0-9].txt commmonname.txt
Upvotes: 1