-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path,image-move-3
executable file
·65 lines (55 loc) · 2.47 KB
/
,image-move-3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/bin/bash
# I have a Parent directory (where i will execute the script from) and inside it (1) markdown files that have the same name as the
# directory name in (2) have multiple directories with each directory have an image called Untitled, Untitled 1, and so on
# if have multiple images in same directory and some have mp4 videos.
#
# I want to rename those images only based on their directory name.
# Then move all of those into images and videos one directory called assets, after that delete the old (now empty) directories.
# And then update/rename the image references stored in markdown files (with the same name as the directory name) in the Parent directory
#
# How will i do this using bash script. Use find and sed.
#
# Here is the initial script:
set -e
if [ "$#" -ne 2 ]; then
echo "Usage: $0 <from_dir> <to_dir>"
exit 1
fi
# from_dir=$(find "$1" -type d \( -exec sh -c 'ls -1 "{}" | grep -q -E "\.(jpg|jpeg|png|gif|mp4)$"' \; \) -print0)
from_sourcedir="$1"
to_destdir="$2"
mkdir -p "$to_destdir/assets"
echo "Extracting..."
# store directories with images, videos, etc. in an array
dir_with_assets=()
while IFS= read -r -d '' dir; do
dir_with_assets+=("$dir")
dirname=$(basename "$dir")
# from dir_with_assets, find rename images to their directory name
find "$dir" -type f \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" -o -iname "*.mov" -o -iname "*.webp" -o -iname "*.gif" -o -iname "*.mp4" \) -print0 | while IFS= read -r -d '' file; do
# rename images to their directory name and move them to to_destdir
# handle conflict names by adding a number
if [ -f "$to_destdir/assets/$dirname" ]; then
i=1
while [ -f "$to_destdir/assets/$dirname-$i" ]; do
((i++))
done
mv -n "$file" "$to_destdir/assets/$dirname-$i"
echo "Renaming $file to $to_destdir/assets/$dirname-$i"
continue
fi
# if new
mv -n "$file" "$to_destdir/assets/$dirname"
echo "Renaming $file to $to_destdir/assets/$dirname"
# handle renaming image references in markdown files
echo "Updating image references in markdown files..."
find "$from_sourcedir" -type f -name "$dirname.md" -print0 | while IFS= read -r -d '' file; do
# update image references in markdown files
sed -i "s/!\[.*\](.*\/)*Untitled.*\(\.jpg\|\.jpeg\|\.png\|\.gif\|\.mp4\|\.webp\|\.mov\)//g" "$file"
done
done
done < <(find "$from_sourcedir" -type d -print0)
if [ ${#dir_with_assets[@]} -eq 0 ]; then
echo "Error: No directories found."
exit 1
fi