this post was submitted on 16 Apr 2025
13 points (100.0% liked)

Linux 101 stuff. Questions are encouraged, noobs are welcome!

1262 readers
3 users here now

Linux introductions, tips and tutorials. Questions are encouraged. Any distro, any platform! Explicitly noob-friendly.

founded 2 years ago
MODERATORS
 

I've tried various versions of these:

FILENAME has spaces

touch -d "$(stat 'FILENAME' | grep -oP 'Birth:\s+\K\d{4}\-\d{2}\-\d{2}' | sed 's/^/"/;s/$/"/')" $(echo 'FILENAME' | sed 's/^/"/;s/$/"/')

FILENAME has no spaces

touch -d "$(stat 'FILENAME' | grep -oP 'Birth:\s+\K\d{4}\-\d{2}\-\d{2} \d{2}:\d{2}' | sed 's/\-//g;s/://g;s/ //')" "FILENAME"

the former returns error about wrong time format.

the latter ended up setting the mtime date to May 10 2446 (at least the millennium is right....) i can't even figure out how the numbers would rearrange/misread to get that from desired Jan 6 2025. So i assume it was read as some kind of offset from 1970 but I don't know enough to use that info to my advantage.

when i echo the commands, the formatting and syntax seems to match examples in the web. so I'm lost.

and I can't seem to find specific docs about touch vis-à-vis what time format is accepted and details of syntax.

btw I'm ND, and can't mentally process manpages docs, at least not dynamically enough to use the info in original or niche situations without also having stackoverflow or other q&a pages with directly relevant examples. ND/OCD is also why i need to sort files by mtime specifically. "just sort it by ctime" is not an option.

anyone who replies, thank you very much.

top 2 comments
sorted by: hot top controversial new old
[–] [email protected] 4 points 1 month ago (1 children)

TLDR: touch -d "@$(stat -c %W "FILENAME")" "FILENAME"

You were going along the right lines, but I think you got yourself tangled somewhere. The documentation about time formats in the man pages isn't great, so you didn't miss much there!

For a lot of utils that take a time format using '@' is the most reliable and precice, so that's what I'm using here.

The stat command can return the creation (birth) time of the file as seconds past the epoch, and we use -c %W to get it to return only that, so we don't need to use grep to parse it.

I hope that's reasonably clear, but let me know if I can explain it better.

[–] [email protected] 1 points 1 month ago

awesome! that worked perfectly! thank you!

now i can finally start working on scripting it to update a whole folder.