user2603941
user2603941

Reputation: 21

Bash loop for getting the first 12 characters in a filename, using the output to run touch -t command for each file

I've got a series of files in the following format:

YYYYMMDDHHmmXXXXXX.m4a in a directory

I'd like to write a script that will allow me to store each filename as a variable, let's call it MyFile, then store "YYYMMDDHHmm" (first 12 charachters of each file) as a variable, let's call it TimeStamp and use it to update the Date Created data for each file in the loop. The command should look something like:

touch -t TimeStamp Myfile.m4a

I'm new to writing scripts and have written the following which is returning an unexpected end at line 17

#!/usr/bin/env bash

for f in /Users/username/music/M4Atest/*.m4a;

do filename=${f%%.*};

echo ${filename};

for ${filename};

do timestamp="${filename:0:12}";

echo ${timestamp};

done;

Thanks for any help

Upvotes: 2

Views: 832

Answers (1)

Freddy
Freddy

Reputation: 4688

One loop is sufficient and use ${f##*/} to remove the longest prefix pattern */ to get the filename.

#!/bin/bash

shopt -s nullglob  # expands a glob pattern to a null string if the pattern doesn't match
for f in /Users/username/music/M4Atest/*.m4a; do
  filename=${f##*/}
  touch -t "${filename:0:12}" "$f"
done

If you want a safer filename pattern, you could use [0-9][0-9][0-9][0-9][01][0-9][0-3][0-9][0-2][0-9][0-5][0-9]?*.m4a instead of *.m4a. This would make sure your filename contains at least the timestamp plus one character (?) plus any amount of characters (*) followed by the suffix .m4a.

# explanation:
# [0-9][0-9][0-9][0-9][01][0-9][0-3][0-9][0-2][0-9][0-5][0-9]?*.m4a
#    Y    Y    Y    Y   M    M    D    D    H    H    m    m

Upvotes: 2

Related Questions