v01d
v01d

Reputation: 327

Embedding a bash command inside the mv command

I have a directory that contains a list of files having the following format:

Now, I want to implement a bash command which matches the files that start with '240' and renames them so that instead of '240-timestampX.ts' the files look like '240-human-readable-timestampX.ts'.

I have tried the following:

find . -maxdepth 1 -mmin +5 -type f -name "240*"
    -exec mv $0 {$0/240-***and here I want to insert
    either stat -c %y filename or date -d @timestampX***} '{}' \;

I stuck here because I don't know if I can embed a bash command inside the mv command. I know the task may look a bit confusing and over-complicated, but I would like to know if it is possible to do so. Of course I can create a bash script that would go through all the files in the directory and while loop them with changing their respective names, but somehow I think that a single command would be more efficient (even if less readable).

Thank you both Kenavoz and Kurt Stutsman for the proposed solutions. Both your answers perform the task; however, I marked Kenavoz's answer as the accepted one because of the degree of similarity between my question and Kenavoz's answer. Even if it is indeed possible to do it in a cleaner way with omitting the find command, it is necessary in my case to use the respective command because I need to find files older than X units of time. So thank you both once again!

Upvotes: 1

Views: 906

Answers (2)

SLePort
SLePort

Reputation: 15461

In case you want to keep your mmin option, your can use find and process found files with a bash command using xargs :

find . -maxdepth 1 -mmin +5 -type f -name "240*.ts" | xargs -L 1 bash -c 'mv "${1}" "240-$(stat -c %y ${1}).ts"' \;

Upvotes: 3

Kurt Stutsman
Kurt Stutsman

Reputation: 4034

In bash if all your files are in a single directory, you don't need to use find at all. You can do a for loop:

for file in 240-*; do
    hr_timestamp=$(date -d $(echo "$file" | sed 's/.*-\([0-9]*\)\.ts/\1/'))
    mv "$file" "240-$hr_timestamp.ts"
done

Upvotes: 2

Related Questions