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.
-
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/
-
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
-
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
-
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.