Skip to content

Instantly share code, notes, and snippets.

@obsessedcake
Last active December 5, 2023 11:08
Show Gist options
  • Save obsessedcake/7fcebb4327d69bd8011abbc77c6c71cf to your computer and use it in GitHub Desktop.
Save obsessedcake/7fcebb4327d69bd8011abbc77c6c71cf to your computer and use it in GitHub Desktop.
2019-11-07
#!/usr/bin/env bash
getFinalFilename () {
local -r filename="${1}"
local -r ext="${2}"
local -r idx="${3}"
if [[ -z "${idx}" ]]; then
local -r newFilename="${filename}.${ext}"
if [[ ! -f "${newFilename}" ]]; then
echo "${newFilename}"
else
getFinalFilename "${filename}" "${ext}" "1"
fi
else
local -r newFilename="${filename}-${idx}.${ext}"
if [[ ! -f "${newFilename}" ]]; then
echo "${newFilename}"
else
getFinalFilename "${filename}" "${ext}" "$((idx + 1))"
fi
fi
}
renameFile () {
local -r filename="${1}"
# Filename format: {yyyy}-{mm}-{dd}_{hh}h-{mm}m-{ss}s-{somehash}.{ext}
local -r regex="([0-9]{4})-([0-9]{2})-([0-9]{2})_([0-9]{2})h-([0-9]{2})m-([0-9]{2})s-.*\.([0-9a-zA-Z]+)"
if [[ "${filename}" =~ ${regex} ]]; then
local -r year="${BASH_REMATCH[1]}"
local -r month="${BASH_REMATCH[2]}"
local -r day="${BASH_REMATCH[3]}"
local -r hours="${BASH_REMATCH[4]}"
local -r minutes="${BASH_REMATCH[5]}"
local -r seconds="${BASH_REMATCH[6]}"
local -r ext="${BASH_REMATCH[7]}"
local newFilename="${year}-${month}-${day}_${hours}-${minutes}-${seconds}"
newFilename="$(getFinalFilename "${newFilename}" "${ext}")"
echo "${filename} -> ${newFilename}";
mv "${filename}" "${newFilename}"
return 0
fi
echo "${filename} doesn't match {yyyy}-{mm}-{dd}_{hh}h-{mm}m-{ss}s-{???}.{ext} pattern." >&2
return 1
}
forEachFile () {
local -r oldPwd="${PWD}"
cd "${1}"
while IFS= read -r file ; do
renameFile "${file}"
done < <(find . -type f -printf "%f\n" 2>/dev/null | sort)
cd "${oldPWd}"
}
forEachFile "${1}"
@obsessedcake
Copy link
Author

obsessedcake commented Dec 5, 2023

I wanted to scrap some instagram pages for the scientific purposes, so I found a instagram-scraper tool that can perfectly do this. I read the manual and found that this line should do what I need (almost):

$ instagram-scraper <username> -d ~/Downloads/ -n -T {year}-{month}-{day}_{h}-{m}-{s}

Unfortunately this has two drawbacks:

  1. h, m and s appends to hours, minutes and seconds respectively. Not what I want.
  2. Doesn't work for posts with more than one media. I think, because, when it tries to save other media, it founds out, that the file with exact same name already exists.

The second issue I fixed this way:

$ instagram-scraper <username> -d ~/Downloads/ -n -T {year}-{month}-{day}_{h}-{m}-{s}-{urlname}

To fix the first one I wrote this bash script.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment