From d4b7c2249ffe5cacd1c0b5bbb545350340849665 Mon Sep 17 00:00:00 2001 From: Haffel Date: Tue, 9 Sep 2025 11:58:03 +0200 Subject: [PATCH] add inverse --- rename-nested-file-to-parent.md | 44 +++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/rename-nested-file-to-parent.md b/rename-nested-file-to-parent.md index c1600c0..dccd409 100644 --- a/rename-nested-file-to-parent.md +++ b/rename-nested-file-to-parent.md @@ -21,3 +21,47 @@ for dir in */; do fi done ``` + + +--- + + +> Rename parent folder to nested mp4 + +```bash +#!/bin/bash + +# Loop through each subdirectory in the current directory +for dir in */; do + # Check if it's a directory + if [[ -d "$dir" ]]; then + # Find the first .mp4 file in the directory + mp4_file=$(find "$dir" -maxdepth 1 -type f -name '*.mp4' | head -n 1) + + # If a .mp4 file is found + if [[ -n "$mp4_file" ]]; then + # Get the file's basename without path and extension + mp4_base_name="$(basename "${mp4_file}" .mp4)" + + # Trim the trailing slash from the directory name + trimmed_dir_name="${dir%/}" + + # New directory name will be the name of the .mp4 file + new_dir_name="${mp4_base_name}" + + # Rename the directory, only if new directory name is different than the original + if [[ "$trimmed_dir_name" != "$new_dir_name" ]]; then + # Check if target directory name already exists + if [[ ! -d "$new_dir_name" ]]; then + mv -n "$dir" "$new_dir_name" + echo "Renamed directory '$dir' to '$new_dir_name'" + else + echo "Cannot rename '$dir' to '$new_dir_name' because the target directory already exists." + fi + fi + else + echo "No .mp4 file found in $dir" + fi + fi +done +```