Skip to content
Advertisement

Linux Command Line – list all directories containing .js files, and copy the directories and their contents to a new folder

Here is the code I already have that finds and lists all directories containing .js files (excluding the node_modules directory).

find . -name '*.js*' -printf "%hn" | sort -u | grep -v node_modules

As you can see, listing those directories is no problem. However, rather than list the directories, I would like to copy them (and their contents) to a new folder, preferably all in one line without running any kind of script.

Any help would be much appreciated!

Advertisement

Answer

The safest way to do this is to process the list of directories using NULL as the delimiter so that directories with spaces (and other odd characters) are handled correctly.

Remove the echo if the output looks correct.

“1-liner”

 find "/path/to/tld" -path "*node_modules*" -prune -o -name "*.js" -printf "%h" | 
    sort -uz | xargs -0 -I _ echo cp -a _ "/path/to/new/dir"

Bash Script

This requires Bash 4 for the associative array which will filter out duplicates.

#!/bin/bash

tld="/path/to/top/level/dir"
newdir="/path/to/new/dir"

unset dirHash;
declare -A dirHash

while read -r -d $'' dir; do
  (( ! dirHash["$dir"]++ )) && echo cp -a "$dir" "$newdir"
done < <(find "$tld" -path "*node_modules*" -prune -o -name "*.js" -printf "%h")
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement