Monday, 9 December 2019

linux - How do I copy file named starting with a dot?


I am trying to copy all files under directory A to directory B. All files under directory A are starting with dot, for example:


A/.a
A/.b
A/.c

which I found if I use: cp A/* B, always get error:


cp: cannot stat 'A/*': no such file or directory

It seems there is no option for cp as ls to handle entries started with dot, anyone has idea how to fix it?



Answer



The reason is because in bash, * does not include files starting with dot (.).


You can run


cp A/.* B

It will warn you that it did not copy . or .., or any subdirectories, but this is fine.


Or, if you want to copy dot files and normal files together, run


cp A/.* A/* B

You could also run


shopt -s dotglob
cp A/* B

which will work in bash, but not sh.


And if you don't mind subdirectories being copied too, then this is the easiest:


cp -R A/ B

Tip: If ever wildcards aren't doing what you expect, try running it with echo, e.g.


$ echo A/*
A/file1 A/file2

$ echo A/.*
A/. A/.. A/.hidden1 A/.hidden2

$ echo A/.* A/*
A/. A/.. A/.hidden1 A/.hidden2 A/file1 A/file2

$ shopt -s dotglob
$ echo A/*
A/file1 A/file2 A/.hidden1 A/.hidden2

No comments:

Post a Comment

How can I VLOOKUP in multiple Excel documents?

I am trying to VLOOKUP reference data with around 400 seperate Excel files. Is it possible to do this in a quick way rather than doing it m...