How to copy hidden (starting with a dot) files and subdirectories in linux?
As long as you're only looking for hidden files and folders at the level of A and don't want, for example
A/b/.hidden
to be copied, you should be able to use this:
cp -r A/.[^.]* B
It basically means copy anything that starts with a .
and then any character other than a .
That filters out .
and ..
Edit: Removed the -p from the cp command since Asker hasn't indicated he wants to preserve any ownerships, dates, etc.
The problem with A/.*
is that there is the directory .
in A
which also matches the pattern.
You can turn on extended glob patterns and use the following:
shopt -s extglob
cp -r A/.!(?(.)) B
It matches files whose name starts with a dot and whose second character is neither a dot nor nothing ( ?(.) matches nothing or a dot, !(...) negates it, i.e. !(?(.)) matches everything else than nothing or a dot).
For cases like this would recommend using find
instead of cp
like this:
find A/ -type f -maxdepth 1 -name '.*' -exec cp -p {} B/ \;
The basic syntax breaks down like this:
find A/ -type f
:find
items in the directoryA/
whose type is a file (instead of a directory)…-maxdepth 1 -name '.*'
: To this for amaxdepth
of 1 directories and whosename
begins with.
.-exec cp -p {} B/ \;
: And once these files are found,exec
thecp
command with a-p
flag to preserve dates/times from the source ({}
) to the destination ofB/
.
I like using maxdepth
to add a layer of control so I am not accidentally copying a whole filesystem. But feel free to remove that.