You shouldn't be using ls
for this. Parsing the output of ls
is unreliable at best, dangerous at worst. See Why not parse ls
(and what to do instead)?
Try find
instead. e.g. with GNU find
(and GNU cp
):
find ./ -maxdepth 1 -regextype awk \
! -regex './(|\.env|\.dockerfile)' \
-exec echo cp -t ../new_directory/ {} +
I use -regextype awk
because I'm very used to the regular expression dialect in awk and I don't want to waste time figuring out the exact dialect used in find-default
. -regextype egrep
would have worked just as well. You can get a list of dialects available by running find -regextype help
(unfortunately, PCRE isn't one of them).
The -regex ...
excludes ./
, ./env
, and ./dockerfile
. Note that neither ^
nor $
anchors are required, they're implicit with find
's -regex
predicate, so you only get exact matches. If you want partial matches, you have to add .*
to the beginning and/or end of your regular expression. This is why I had to include the ./
in the regex.
If I were to run this from the parent, directory, it would have to be written as:
find folder1/ -maxdepth 1 -regextype awk \
! -regex 'folder1/(|\.env|\.dockerfile)' \
-exec echo cp -t ../newfolder {} +
or with some other pattern that matched the path, e.g. '.*/(|\.env|\.dockerfile)'
.
The echo
makes this a dry-run, to show you what would be copied without actually copying them. Remove it when you've confirmed the command will do what you want.
GNU cp
's -t
option allows you to specify the target directory before the list of files to be copied.
ls
flag to show files that start with a.
– cutrightjm Jun 29 '22 at 13:09ls
" link. – Kamil Maciorowski Jun 29 '22 at 15:54