Bash script to move first N files with specific name

Viewed 543

I'm trying to move only 100 files with a specific extensions (from the current directory to the parent directory), but the following attempt of mine does not work

for file in $(ls -U | grep *.txt | tail -100)
do
    mv $file ../
done

Can you point me to the correct approach?

3 Answers

Since you didn't quote *.txt, the shell expanded it to all the filenames ending in .txt. So your command is something like:

ls -U | grep file1.txt file2.txt file3.txt ... | tail -100

Since grep has filename arguments, it ignores its standard input. It outputs all the lines matching file1.txt in the remaining files. There's probably no matches, so nothing is piped to tail -100. And even if there were matches, the output would be the lines from the files, not filenames, so it wouldn't be useful for the mv command.

You can loop over the filenames directly, and use a counter variable to stop after 100 files.

counter=0
for file in *.txt
do
    if (( counter >= 100 ))
    then break
    fi

    mv "$file" ../
    ((counter++))
done

This avoids the pitfalls of parsing the output of ls.

this will do the job:

ls -U *.txt | tail -100 | while read filename; do mv "$filename" ../; done

while read filename respect spaces in the filename.

Run this in the text file directory:

#!/bin/bash

for txt_file in ./*.txt; do
        ((c++==100)) && break
        mv "$txt_file" ../
done
Related