I have a file list like this (long list, not all):
And I want to filter the files with keywords "QM" and ".h5", so I type ls|grep "QM"|grep "h5"
and it shows these (what I need)
So basically I want to move these files to another directory, but I don't know how to move them with one line of script.
Also, is there a way to randomly choose 5 of these files and copy them to another directory?
"Many files"? "Files with funny characters in their name"?
This calls for
find
andxargs
!Read
man find;man xargs
and do something like:Note: "
AnotherDirectory
" must already exist.Note: See what the results will be by initaiily replacing "
mv
" with "echo mv
".Shell globs are going to be your friends here.
For example, instead of using
grep
, you can list all files whose names containQM
and end with.h5
usingYou can use globs in
mv
andcp
operations provided that the number of matching files is not too largeIf the number of files is too large, you may get an
argument list too long
error; you can work around that using the shell'sprintf
builtin withxargs
to break the copy into manageable chunks:With bash, there's no intrinsic way to limit the number of files selected (or to select a random subset) but you could do so by adding a call to
shuf
:Note that I used the null byte
\0
instead of the newline character to delimit the list of filenames - that's not necessary in your case, but makes the command usable in the more general case where filenames themselves may contain newlines.If you don't mind switching to the z shell
zsh
, then you can select a random subset without resorting to external utilities, using the shell's more expressive glob qualifiers:Related question on our Unix & Linux sister site:
Just
cp *QM*.h5 target_dir
and done.