command line find first file in a directory command line find first file in a directory bash bash

command line find first file in a directory


You can go inside each dir and run:

$ mv `ls | head -n 1` ..


If first means whatever the shell glob finds first (lexical, but probably affected by LC_COLLATE), then this should work:

for dir in */; do    for file in "$dir"*.jpg; do        echo mv "$file" "${file%/*}.jpg" # If it does what you want, remove the echo        break 1    donedone

Proof of concept:

$ mkdir dir{1,2,3} && touch dir{1,2,3}/file{1,2,3}.jpg$ for dir in */; do for file in "$dir"*.jpg; do echo mv "$file" "${file%/*}.jpg"; break 1; done; donemv dir1/file1.jpg dir1.jpgmv dir2/file1.jpg dir2.jpgmv dir3/file1.jpg dir3.jpg


Look for all first level directories, identify first file in this directory and then move it one level up

find . -type d \! -name . -prune | while read d; do    f=$(ls $d | head -1)    mv $d/$f .done