Home > OS >  How to find all .PNG files and move them in new folders like 1,2,3,4,5.. (one file per folder)
How to find all .PNG files and move them in new folders like 1,2,3,4,5.. (one file per folder)

Time:10-03

I would like to find .png files in current sub-folders and move them in new folders. I need one .png file, per single folder. Folders needs to be auto-created. I tried something like below, but doesn't work. Please help me.

#!/bin/bash
find . -name "*.png" -print0 | \
sort -z --version-sort | \
xargs -0n1 bash -c 'TARGET=target-$((${1//[^0-9]/} "/ 0   1)); \
mkdir -p "$TARGET"; \
mv -t "$TARGET" "$@"' move-1

CodePudding user response:

I suggest to use a counter in a while loop:

find . -name "*.png" -print0 |
  while IFS= read -r -d '' f ; do
    c=$((c 1));
    mkdir "$c";
    mv -v "$f" "$c";
  done

CodePudding user response:

Something like this.

#!/usr/bin/env bash

n=1
find . -name '*.png' -print0 | {
  while IFS= read -rd '' pic; do
    while [[ -e $n ]]; do
      ((n  ))
    done
    mkdir -vp "$n" && mv -v "$pic" "$n"
  done
}

Tested against the files and directories, created by:

#!/usr/bin/env bash

mkdir -p foo/bar/baz/more/qux

touch foo/bar/{a..c}.png
touch foo/bar/baz/{d..f}.png
touch foo/bar/baz/more/{g..i}.png
touch foo/bar/baz/more/qux/{j..l}.png

Output

mkdir: created directory '1'
renamed './foo/bar/a.png' -> '1/a.png'
mkdir: created directory '2'
renamed './foo/bar/b.png' -> '2/b.png'
mkdir: created directory '3'
renamed './foo/bar/baz/d.png' -> '3/d.png'
mkdir: created directory '4'
renamed './foo/bar/baz/e.png' -> '4/e.png'
mkdir: created directory '5'
renamed './foo/bar/baz/f.png' -> '5/f.png'
mkdir: created directory '6'
renamed './foo/bar/baz/more/g.png' -> '6/g.png'
mkdir: created directory '7'
renamed './foo/bar/baz/more/h.png' -> '7/h.png'
mkdir: created directory '8'
renamed './foo/bar/baz/more/i.png' -> '8/i.png'
mkdir: created directory '9'
renamed './foo/bar/baz/more/qux/j.png' -> '9/j.png'
mkdir: created directory '10'
renamed './foo/bar/baz/more/qux/k.png' -> '10/k.png'
mkdir: created directory '11'
renamed './foo/bar/baz/more/qux/l.png' -> '11/l.png'
mkdir: created directory '12'
renamed './foo/bar/c.png' -> '12/c.png'

CodePudding user response:

You can keep your logic and integrate with below logic. Here is full command

find . -type f -name "*.png" -print -exec mkdir {}.folder   \;  | xargs -I {} mv {} {}.folder
  • Below command will find png, -exec will create folder. -print is important to pass result next XARGS.
find . -type f -name "*.png" -print -exec mkdir {}.folder   \;
  • And this line will move files accordingly to next folder.
xargs -I {} mv {} {}.folder

You can change folder path accodring your requirement.

  • Related