How to move all files whose contents begin with 0?

Here’s a command to move all files whose name begin with 0 into a folder called zero :

mv [0]* zero

Question: What is a command for moving all files whose contents begin with 0 into a folder called zero?

Hopefully, there is a short command doing that also.

I know that the first character of the contents of a file is given by head -c 1 filename.

There isn’t a command to do this. However, it’s a straightforward piece of scripting.

  1. Work out how to identify a file by its contents and move it:

    f=example_file.txt
    b=$(head -c1 <"$f")
    [ "$b" = "0" ] && echo mv -- "$f" zero/
    
  2. Work out how to iterate across all the 100,000 files in the directory:

    find . -maxdepth 1 -type f -print
    

    Or maybe your shell allows you to use a wildcard for a large number of entries and the simpler more obvious loop will work:

    for f in *
    do
        echo "./$f"
    done
    
  3. Work out how to run the mv code for each possible file:

    find -maxdepth 1 -type f -exec sh -c '
        b=$(head -c1 "$1")
        [ "$b" = "0" ] && echo mv -- "$1" zero/
    ' _ {} ;
    

    Or

    for f in *
    do
        [ "$(head -c1 "$f")" = "0" ] && echo mv -- "$f" zero/
    done
    
  4. Optimise the find version:

    find -maxdepth 1 -type f -exec sh -c '
        for f in "$@"
        do
            [ "$(head -c1 "$f")" = "0" ] && echo mv -- "$f" zero/
        done
    ' _ {} +
    

In all cases remove echo to change the command from telling you what it would do, to doing it.

Answered By: Chris Davies
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.