Skip to content

Snippets

1 yr. ago

File safe date string

Javascript

Returns a date time string that is safe to use for filenames.

date
filename
utility
file-safe-date-string.js
// output: 2025-04-04_17-44-19
const getFileSafeDateString = () => {
const date = new Date();
const time = date.toLocaleTimeString(undefined, { hour12: false });
const hour = time.slice(0, 2);
const utcDate = new Date().toISOString();
const updatedDateHour = utcDate.replace(/T\d+/, `_${hour}`);
const formattedDate = updatedDateHour.replace(/:/g, "-");
return formattedDate.split(".")[0];
}
3 mo. ago

Photoshop auto-fit layer

Javascript
Markdown

Instantly resize layer to fit your artboard.

auto-fit
images
layers
photoshop
  • Script
  • Action instructions
photoshop-auto-fit-layer.jsx
#target photoshop
var doc = app.activeDocument;
var layer = doc.activeLayer;
var bounds = layer.bounds;
var layerWidth = bounds[2].as('px') - bounds[0].as('px');
var layerHeight = bounds[3].as('px') - bounds[1].as('px');
var scaleW = (doc.width.as('px') / layerWidth) * 100;
var scaleH = (doc.height.as('px') / layerHeight) * 100;
var finalScale = Math.min(scaleW, scaleH);
layer.resize(finalScale, finalScale, AnchorPosition.MIDDLECENTER);
layer.translate(doc.width/2 - (bounds[0] + bounds[2])/2, doc.height/2 - (bounds[1] + bounds[3])/2);
12 mo. ago

Outlook group to CSV

Javascript

Parses a semicolon-separated string of contact entries from an expanded Outlook distribution list into a CSV format.

csv
email
parser
outlook-group-to-csv.js
import fs from "fs";
const input = `Abercrombie, Clarence L. <AbercrombieCL@email.com>; Abushawish, Maysaa Z <abushawishmz@email.com>; Adams, Benjamin <adamsbj@email.com>; Anderson, A.K. <AndersonAK@email.com>; Bond, Sr., Jamie <bondje@email.com>; Castilla Candil, Luis <castillacandillm@email.com>; Castillo-Bernal, Melba <castillobernalmd@email.com>; Chang, Shun-Yao <changs@email.com>; Chou, Yi Jou <chouy@email.com>; Crouse, Sr, Jake W. <crousejw@email.com>; Richards, Jr., Robert C <RichardsRC1@email.com>`;
function parseOutlookGroupToCsv() {
const lines = input
.split(";")
.map((entry) => entry.trim())
.filter(Boolean)
.map((entry) => entry.replace(/\b(Jr\.?|Sr\.?|II|III|IV|V),?/gi, "").trim())
.map((entry) => {
const match = entry.match(/^(.*?),\s*(.*?)\s*<([^>]+)>$/);
if (!match) return null;
let [_, lastName, firstPart, email] = match;
if (/test/i.test(email)) return null;
let nameParts = firstPart.split(/\s+/);
if (nameParts.every((p) => /^[A-Z](\.?)$/.test(p))) {
return `${lastName},${nameParts.join(" ")},${email}`;
}
nameParts = nameParts.filter((p) => !/^[A-Z]\.?$/.test(p));
const firstName = nameParts.join(" ");
return `${lastName},${firstName},${email}`;
})
.filter(Boolean);
return ["lastName,firstName,email", ...lines].join("\n");
}
const csv = parseOutlookGroupToCsv();
fs.writeFileSync("output.csv", csv);
1 yr. ago

Remove whitespace svg

Javascript
HTML

Paste svg to remove unnecessary whitespace.

cleanup
svg
viewBox
whitespace
  • Script
  • Markup
remove-whitespace-svg.js
const originalSvg = document.querySelector("#originalSvg");
const newSvg = document.querySelector("#newSvg");
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
originalSvg.addEventListener("paste", async () => {
await delay(1);
const tempContainer = document.createElement("div");
tempContainer.innerHTML = originalSvg.value;
document.body.appendChild(tempContainer);
await delay(1);
const svg = tempContainer.querySelector("svg");
if (svg) {
const { x, y, width, height } = svg.getBBox();
svg.setAttribute("viewBox", `${x} ${y} ${width} ${height}`);
newSvg.value = svg.outerHTML;
}
tempContainer.remove();
});
3 mo. ago

Photoshop batch resize images

Javascript

Batch resize images to a specific canvas size, centers them and exports them as a png or jpg.

batch
images
photoshop
photoshop-batch-resize-images.jsx
#target photoshop
// update these vars below: targetW, targetH
// toggle comment Save as PNG or JPG
(function () {
// Prompt user to select input folder
var inputFolder = Folder.selectDialog("Select the folder with images to process:");
if (!inputFolder) {
alert("No folder selected. Exiting.");
return;
}
// Prompt user to select output folder
var outputFolder = Folder.selectDialog("Select the folder to save processed images:");
if (!outputFolder) {
alert("No output folder selected. Exiting.");
return;
}
var files = inputFolder.getFiles(/\.(jpg|jpeg|png|tif|tiff|bmp)$/i);
if (files.length === 0) {
alert("No image files found in selected folder.");
return;
}
// Set target canvas dimensions
var targetW = 1500;
var targetH = 1000;
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!(file instanceof File)) continue;
var doc = open(file);
app.activeDocument = doc;
doc.changeMode(ChangeMode.RGB);
// Resize proportionally to fit inside target dimensions
var w = doc.width.as("px");
var h = doc.height.as("px");
var scale = Math.min(targetW / w, targetH / h);
doc.resizeImage(UnitValue(w * scale, "px"), UnitValue(h * scale, "px"), null, ResampleMethod.BICUBIC);
// Create transparent canvas
var tempDoc = app.documents.add(
targetW, targetH, doc.resolution, "TempCanvas", NewDocumentMode.RGB, DocumentFill.TRANSPARENT
);
// Copy/paste from resized image
app.activeDocument = doc;
doc.selection.selectAll();
doc.selection.copy();
doc.close(SaveOptions.DONOTSAVECHANGES);
app.activeDocument = tempDoc;
tempDoc.paste();
var layer = tempDoc.activeLayer;
// Center the pasted layer
var dx = (targetW - (layer.bounds[2].as("px") - layer.bounds[0].as("px"))) / 2 - layer.bounds[0].as("px");
var dy = (targetH - (layer.bounds[3].as("px") - layer.bounds[1].as("px"))) / 2 - layer.bounds[1].as("px");
layer.translate(dx, dy);
// Save as PNG
var saveFile = new File(outputFolder + "/" + decodeURI(file.name).replace(/\.[^\.]+$/, "") + ".png");
var pngOptions = new PNGSaveOptions();
pngOptions.compression = 9;
pngOptions.interlaced = false;
tempDoc.saveAs(saveFile, pngOptions, true, Extension.LOWERCASE);
// Save as JPG
// var saveFile = new File(outputFolder + "/" + decodeURI(file.name).replace(/\.[^\.]+$/, "") + ".jpg");
// var jpgOptions = new JPEGSaveOptions();
// jpgOptions.quality = 12;
// jpgOptions.formatOptions = FormatOptions.STANDARDBASELINE;
// jpgOptions.embedColorProfile = true;
// jpgOptions.matte = MatteType.NONE;
// tempDoc.saveAs(saveFile, jpgOptions, true, Extension.LOWERCASE);
tempDoc.close(SaveOptions.DONOTSAVECHANGES);
}
alert("Done! Saved " + files.length + " images as " + targetW + "x" + targetH + " to:\n" + outputFolder.fsName);
})();
1 yr. ago
Javascript

Extract text and links from anchor tags and generate HTML in a new window.

links
dom
url
scrape-links-from-url.js
// Refine the selector for a more specific search
const anchors = Array.from(document.querySelectorAll("a"));
const linkData = anchors.map(anchor => {
const nameText = anchor.textContent?.replace(/\s+/g, " ").trim() || "";
const cleanLink = anchor.href;
return [nameText, cleanLink];
}).filter(([name, link]) => name && link);
function makeViews() {
const list = `<ul>${linkData.map(([name, link]) =>
`<li><a href="${link}" target="_blank">${name}</a></li>`).join("")}</ul>`;
const paragraph = linkData.map(([name, link]) =>
`<p><a href="${link}" target="_blank">${name}</a></p>`).join("");
const tableRows = linkData.map(([name, link]) =>
`<tr><td>${name}</td><td><a href="${link}" target="_blank">${link}</a></td></tr>`).join("");
const table = `
<table border="1" style="border-collapse: collapse; width: 100%;">
<thead>
<tr>
<th>Name</th>
<th>Links</th>
</tr>
</thead>
<tbody>
${tableRows}
</tbody>
</table>
`;
const newWindow = window.open("");
if (newWindow) {
// Change to desired view (list, paragraph, table)
newWindow.document.body.innerHTML = paragraph;
}
}
makeViews();
1 yr. ago

Expand scrollable elements

CSS

Make all elements fully visible by removing scroll, position and height limits for screenshots.

height
overflow
position
screenshot
scroll
expand-scrollable-elements.css
* {
overflow: visible !important;
height: auto !important;
max-height: none !important;
position: static !important;
}
1 yr. ago

Responsive table

CSS
HTML

Responsive table that stacks on mobile.

table
  • Styles
  • Markup
responsive-table.css
@media (max-width: 800px) {
.table-vertical tbody tr {
display: flex;
flex-direction: column;
padding-top: calc(0.25rem + 8px);
border-bottom: 1px solid #eee;
}
.table-vertical tbody tr td:nth-of-type(1) {
width: fit-content;
margin-bottom: 0.5rem;
padding: 0.25rem 0.5rem;
background-color: rgba(138, 110, 75, 0.2);
font-size: 16px;
border-radius: 0 5px 5px 0;
}
.table-vertical tbody tr td:nth-of-type(2) {
padding-left: 0.5rem;
font-weight: bold;
border-top: none;
}
}
1 yr. ago
Shell

Regex pattern to add link text to title attribute.

regex
url
  • Pattern
  • Replacement
add-title-attribute-to-link-pattern.sh
# Find all <a> tags and capture href and text into groups 1, 2
# $1 is ([^"]+) matches any character except "
# $2 is ([^<]+) matches any character except <
<a\s+href="([^"]+)"[^>]*>([^<]+)</a>
1 yr. ago

Responsive grid columns

CSS

Responsive, equally sized grid columns that wrap for mobile.

grid
responsive-grid-columns.css
.el {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(min(300px, 100%), 1fr));
gap: 20px;
}
1 yr. ago

Add user to group

Shell

Manage user group membership and permissions to ensure proper access control over directories and files.

chmod
chown
permissions
usermod
  • usermod
  • chown
  • group permissions
  • setgid
add-user-to-group-01.sh
# Add user to primary_group
sudo usermod -aG primary_group user
12 mo. ago

Compress video

Shell

Compress a video using the H.265 (HEVC) codec for a balance of quality and size.

compression
ffmpeg
compress-video.sh
# Input: input.mp4
# Video codec: x265 (HEVC)
# CRF: 28 (default), recommended range 18-28
# Encoding preset: medium (default), faster|fast|medium|slow|slower, etc.
# Audio codec: aac
# Audio bitrate: 128k (default), 96k|128k|192k|320k
# Video tag: hvc1, can help with compatibility issues
# Output: output.mp4
ffmpeg -i input.mp4 -vcodec libx265 -crf 28 -preset medium -c:a aac -b:a 128k -tag:v hvc1 -metadata creation_time="2024-05-12T14:33:00Z" output.mp4
1 yr. ago

Compress multiple videos script

Shell

A script to compress all videos in a directory using ffmpeg.

ffmpeg
script
  • Shell script
  • Commands
compress-multiple-videos-script.sh
_#!/bin/bash
# Default values
vcodec="libx265"
acodec="aac"
abitrate="128k"
output_format="mkv"
crf=28
preset="medium"
# Dynamic video tag variable
if [[ "$vcodec" == "libx265" ]]; then
video_tag="-tag:v hvc1"
elif [[ "$vcodec" == "libx264" ]]; then
video_tag="-tag:v avc1"
else
video_tag=""
fi
# Function to show usage
usage() {
echo "Usage: $0 [options]"
echo "Options:"
echo " --vcodec [libx264|libx265] Video codec (default: libx265)"
echo " --acodec [aac|mp3] Audio codec (default: aac)"
echo " --abitrate [128k|192k] Audio bitrate (default: 128k)"
echo " --output-format [mp4|mkv] Output format (default: mkv)"
echo " --crf [value] Constant Rate Factor (default: 28)"
echo " --preset [preset] Encoding preset (default: medium)"
echo " --help Show this help message"
exit 1
}
# Parse command-line arguments
while [[ $# -gt 0 ]]; do
case "$1" in
--vcodec)
vcodec="$2"
shift 2
;;
--acodec)
acodec="$2"
shift 2
;;
--abitrate)
abitrate="$2"
shift 2
;;
--output-format)
output_format="$2"
shift 2
;;
--crf)
crf="$2"
shift 2
;;
--preset)
preset="$2"
shift 2
;;
--help)
usage
;;
*)
echo "Unknown option: $1"
usage
;;
esac
done
# Create the output directory if it doesn't exist
mkdir -p output
# Process video files
for file in *.{mp4,mov,avi,mkv}; do
# Skip if no files are found
[ ! -e "$file" ] && continue
# Get creation date from metadata
timestamp=$(ffprobe -v quiet -select_streams v:0 -show_entries format_tags=creation_time -of default=noprint_wrappers=1:nokey=1 "$file")
# Format the timestamp to your desired format YYYY-MM-DD-HH-MM-SS
formatted_timestamp=$(date -j -f "%Y-%m-%dT%H:%M:%S" "${timestamp%.*}" "+%Y-%m-%d-%H-%M-%S" 2>/dev/null)
# If the timestamp is empty, use the current time instead
[ -z "$formatted_timestamp" ] && formatted_timestamp=$(date "+%Y-%m-%d-%H-%M-%S")
# Compress the video
ffmpeg -i "$file" -vcodec "$vcodec" -crf "$crf" -preset "$preset" -c:a aac "$acodec" -b:a "$abitrate" "$video_tag" "output/${formatted_timestamp}.${output_format}"
done
1 yr. ago

Batch resize images

Shell

Batch resize and center images to a specific dimension.

batch
image
imagemagick
magick
batch-resize-images-command.sh
# cd to directory with images
# adjust size as necessary 1427x803 (resize, extent)
# change output directory: ~/Downloads/output/"$file"
for file in *.jpg; do
magick "$file" -gravity center -resize '1427x803^' -extent 1427x803 ~/Downloads/output/"$file"
done
1 yr. ago

Extract screenshot from videos

Shell

Extract screenshot from videos at a specific timestamp using ffmpeg.

ffmpeg
processing
screenshot
extract-screenshot-from-videos.sh
for f in *.mp4; do ffmpeg -ss 5 -i "$f" -frames:v 1 "${f%.mp4}.jpg"; done
2 mo. ago

Find largest files

Shell

List the largest files in a directory with optional limits.

du
filesystem
find
head
  • Function
  • Example
largest-files-function.sh
largest_files() {
local search_dir="${1:-.}"
local num_results="${2:-10}"
echo "Searching in: $search_dir for the top $num_results files..."
/usr/bin/find "$search_dir" -type f -exec /usr/bin/du -ah {} + 2>/dev/null | /usr/bin/sort -rh | /usr/bin/head -n "$num_results"
}
3 mo. ago

Force quit app

Shell

Kill a running application process from the command line using pkill.

pkill
force-quit-app.sh
pkill -f "/Applications/Google Chrome.app"
12 mo. ago

Lighten video

Shell

Use ffmpeg to boost brightness and reduce flickering in dark or shadowy videos using frame interpolation and EQ filters.

brightness
ffmpeg
flickering
shadows
lighten-video.sh
ffmpeg -i input.mp4 -vf "minterpolate=fps=30:mi_mode=mci:mc_mode=aobmc:vsbmc=1,eq=brightness=0.03" -c:a copy output.mp4
1 yr. ago

Find directories by name

Shell

Search for directories matching a specific name pattern across the entire filesystem.

directories
find
search
find-directories-by-name.sh
# change nix for search term
sudo find / -type d -iname '*nix*' 2>/dev/null
1 yr. ago

Monoscopic 360° to stereoscopic 180° video

Shell

Use FFmpeg to transform a monoscopic 360° video into a side-by-side stereoscopic 180° VR format.

ffmpeg
vr
mono-360-to-stereo-180.sh
# change input file: input_360.mp4
# Use HEVC (H.265) for better compression: -c:v libx265
# Increase bitrate for better quality: -b:v 20M
ffmpeg -i input_360.mp4 -filter_complex "
[0:v]v360=input=equirect:output=fisheye:h_fov=180:v_fov=180:yaw=-45[left];
[0:v]v360=input=equirect:output=fisheye:h_fov=180:v_fov=180:yaw=45[right];
[left][right]hstack" -c:v libx264 -crf 18 -preset slow -pix_fmt yuv420p output_vr180.mp4
1 yr. ago

Rsync local and remote examples

Shell
Text

Learn how to sync files between drives or remote systems using rsync.

backup
file sync
rsync
  • Local
  • Remote
  • Exclude list
rsync-local.sh
rsync -av --progress --delete-before --exclude-from="exclude-list.txt" /path/to/HDD1 /path/to/HDD2
1 yr. ago

Paste to file over ssh

Shell

Quickly paste clipboard content into a remote file over ssh using pbpaste and cat.

cat
pbpaste
ssh
paste-to-file-over-ssh.sh
# Content must be on your clipboard before executing
pbpaste | ssh USERNAME@IP_ADDRESS 'cat > /path/to/file/compose.yml'