How can I copy all hidden files/directories in the home directory into a separate directory from command line ? I wasn't able to find a lot of material concerning usage of hidden files .

  • 1
    recursivley or "flat" (meaning: also from subdirectories)? – Jacob Vlijm Jan 25 '15 at 20:55
  • recursively would do the job best, I'd say – user43389 Jan 25 '15 at 20:59

What needs to be done

In principle not a complicated question, however, you need to take care of a few things:

  • You need (as I understand) to copy hidden files/directories recursively
  • You will run into name clashes (duplicate names, I tried)

The (python) script below takes care of both:

  • It searches for files and directories recursively in given (source-) directory
  • it copies found files and directories into a given (target) directory
  • In case of duplicates, it renames them to duplicate_1<filename>, duplicate_2<filename> (or directory-) etc.

The script

#!/usr/bin/env python3
import shutil
import sys
import os

directory = sys.argv[1]
target = sys.argv[2]

def handle(name):
    n = 1; name_orig = name
    while os.path.exists(target+"/"+name):
        name = "duplicate_"+str(n)+"_"+name_orig
        n = n+1
    return target+"/"+name

for root, dirs, files in os.walk(directory):
    for name in files:
        if name.startswith("."):
            subject = root+"/"+name
            newfile = handle(name)
                shutil.copyfile(subject, newfile)
    for dr in dirs:
        if dr.startswith("."):
            subject = root+"/"+dr
            newdir = handle(dr)
                shutil.copytree(subject, newdir)

How to use

Copy the script above into an empty file, save it as search_hidden.py. Run it with the source- and target directories as arguments:

python3 /path/to/search_hidden.py <source_directory> <target_directory>
  • Wow, this seems like a lot of work so thank you so much for your effort and also thank you for providing an explanation ! :) – user43389 Jan 25 '15 at 21:34
  • @user43389 you're welcome! – Jacob Vlijm Jan 25 '15 at 21:35
  • @user43389 Edited the script to prevent it to break on temp files. – Jacob Vlijm Jan 25 '15 at 22:04
  • Just wondering why you would run into "name clashes"? Aren't all the names/paths unique in the source? – MrWhite Jan 26 '15 at 11:43
  • @w3d duplicate names, there are quite a few if you copy them from ~/ recursively (what OP asked for, see comment on the question). – Jacob Vlijm Jan 26 '15 at 11:45

If all the hidden files start with a dot (.), then you can do

cp .?* /path/to/directory

from the directory the hidden files are in. This command says copy all the files starting with a dot (.?*) to the directory specified. '*' is a wildcard.

  • .?* requires at least one character after the dot '.'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.