Delete node_modules folder recursively from a specified path using command line - bash
I have multiple npm projects saved in a local directory. Now I want to take backup of my projects without the node_modules folder, as it is taking a lot of space and can also be retrieved any time using npm install.
So, what would be a solution to delete all node_modules folders recursively from a specified path using the command line interface?
Print out a list of directories to be deleted:
find . -name 'node_modules' -type d -prune
Delete directories from the current working directory:
find . -name 'node_modules' -type d -prune -exec rm -rf '{}' +
Alternatively you can use trash (brew install trash) for staged deletion:
find . -name node_modules -type d -prune -exec trash {} +
Try
https://github.com/voidcosmos/npkill
npx npkill
it will find all node_modules and let you remove them selectively.
Improving on the accepted answer:
find . -name 'node_modules' -type d -prune -exec rm -rf '{}' +
I found that the command above would run a very long time to fetch all folders and then run a delete command. To make the command resumable, I'd suggest using \;. To see progress of the command being run, use -print to see the directory being deleted.
Note: You must first cd into the root directory and then run the command. Or instead of find ., use find {project_directory}.
To delete folders one by one:
find . -name 'node_modules' -type d -prune -exec rm -rf '{}' \;
To delete folders one by one and print the folder being deleted:
find . -name 'node_modules' -type d -prune -print -exec rm -rf '{}' \;
For the people who like an interactive way of doing this, refer to jeckep's answer. Run this in the directory you wish to prune:
npx npkill
I have come across with this solution,
first find the folder using find and specify name of the folder.
execute delete command recursively -exec rm -rf '{}' +
run the following command to delete folders recursively
find /path -type d -name "node_modules" -exec rm -rf '{}' +
When on Windows, I use the following .BAT file to delete node_modules recursively from the current folder:
#for /d /r . %d in (node_modules) do #if exist %d (echo %d && rd %d /s /q)
Or, via CMD.EXE:
>cmd.exe /c "#for /d /r . %d in (node_modules) do #if exist %d (echo "%d" && rd "%d" /s /q)""
bash function to remove node_modules. It will remove all node_modules directories recursively from the current working directory,
while printing found paths.
You just need to put in somewhere in your $PATH
rmnodemodules(){
find . -name 'node_modules' -type d -prune -exec echo '{}' \; -exec rm -rf {} \;
}
In Bash, you can simply use
rm -rf node_modules **/node_modules
If you want to move instead of delete it:
find . -name 'node_modules' -type d -prune -exec mkdir -p ./another/dir/{} \; -exec mv -i {} ./NODE_MODULES/{} \;
This will keep the directory structure.
A simple trick to remove all node_modules folders in your servers (which can reduce a lot of space) is to run:
# For Ubuntu
sudo find / -not -path "/usr/lib/*" -name 'node_modules' -type d -prune -exec rm -rf '{}' +
# For macOS
sudo find / -not -path "/usr/local/*" -name 'node_modules' -type d -prune -exec rm -rf '{}' +
Here we need to exclude /usr/lib/* because if you won’t, it will delete your npm and you need to reinstall it :)
Note: This is just improving on the accepted answer, please use the accepted answer first.
If you are so bored then keep reading.
Basically, this command should work fine for 99% of cases
find . -name 'node_modules' -type d -prune -exec rm -rf '{}' +
I notice that deleting files via the command line is longer than deleting a folder via Finder (when deleting from Finder it moves that folder to ~/.Trash directory).
So if you want to move node_modules to ~/.Trash folder then you can try
find . -name 'node_modules' -type d -prune -exec sh -c 'mv -f "$1" "$(dirname "$1")/$(basename $(dirname "$1"))_$(basename "$1")" && mv "$(dirname "$1")/$(basename $(dirname "$1"))_$(basename "$1")" ~/.Trash/' sh {} \;
as you notice it consist of 2 parts.
find . -name 'node_modules' -type d -prune find all node_module dirs
-exec sh -c 'mv -f "$1" "$(dirname "$1")/$(basename $(dirname "$1"))_$(basename "$1")" && mv "$(dirname "$1")/$(basename $(dirname "$1"))_$(basename "$1")" ~/.Trash/' sh {} \; rename node_module by prefixing it with it's parent folder name and move it to Trash
Before I had
~/Development/angular-projects
┣ project1
┣ project2
┗ project3
After running command
~/.Trash
┣ ~project1_node_modules
┣ ~project2_node_modules
┗ ~project3_node_modules
Then make sure to empty trash
Or Turn On empty trash feature
Python Script to Delete the node_modules folder from multiple projects. Just place it in your project folder consisting multiple projects and run it.
import os
import shutil
dirname = '/root/Desktop/proj' #Your Full Path of Projects Folder
dirfiles = os.listdir(dirname)
fullpaths = map(lambda name: os.path.join(dirname, name), dirfiles)
dirs = []
for file in fullpaths:
if os.path.isdir(file): dirs.append(file)
for i in dirs:
dirfiles1 = os.listdir(i)
fullpaths1 = map(lambda name: os.path.join(i, name), dirfiles1)
dirs1 = []
for file in fullpaths1:
if os.path.isdir(file):
dirs1.append(file)
if(file[-12:]=='node_modules'):
shutil.rmtree(file)
print(file)
Related
How to remove all subdirectories? (unix shell scripting)
I have a directory called "cdrs-roaming". Everyday I receive one or more .zip files and unzip them with this: #!/bin/bash for i in *.zip do j=${i//\.zip/} mkdir $j cd $j unzip ../$i cd - done Then I have for example: "example1.zip" and "example1"; "example2.zip" and "example2" I'm removing all zip files (in this case: "example1.zip" and "example2.zip") with this: #! /bin/bash find /dados/cdrs-roaming/*.zip -mtime +1 -exec rm {} \; So I want to remove the directories (or folders - I really don't know the difference) "example1" and "example2". I've tried this: #! /bin/bash find /dados/cdrs-roaming/ -type d -mtime +1 -exec rm -rf {} \; But it also removes "cdrs-roaming". I've also tried to use: find /cdrs-roaming/ -type d -mtime +1 -exec rm -rf {} \; But it returns: find: ‘/cdrs-roaming/’: No such file or directory Any idea for doing this? I need to delete only the directories within "cdrs-roaming" but I can't remove anything else inside it (my .sh files are inside of it)
Since you are using bash, how about rm -rf /dados/cdrs-roaming/*/ The final slash ensures that bash only expands the pattern to directories.
Use -mindepth 1 option: find /dados/cdrs-roaming/ -mindepth 1 -type d -mtime +1 -exec rm -rf {} \;
how to delete a file recursively from folders on mac / unix
I want to delete ._DS_Store file from the parent folder and all sub folders. How to delete the .DS_Store file recursively from all folders with single command? (using rm -rf command)
find parent_dir -name .DS_Store -delete With GNU find at least. Otherwise find parent_dir -name .DS_Store -print0 | xargs -0 rm -f Or find parent_dir -name .DS_Store -exec rm -f +
To do this in the current directory you can do find $(pwd) -name .DS_Store -delete or other commands in place of -delete as show in previous answer.
Delete directories with specific files in Bash Script
I would like to delete specific files if existed but also the directories that contain these files. I do know the files I would like to wipe but not the directories. So far, as I'm new in bash scripting, I think of this : find ./ -type f -name '*.r*' -print0 | xargs -0 rm -rf &> log_del.txt find ./ -type f -name '*.c*' -print0 | xargs -0 rm -rf &>> log_del.txt At the moment, all files named with the specific extensions *.r* and *.c* are deleted. But the directories are still remaining and also the subdirectories in it, if existed. I also thought of the option -o in find to delete in one line : find ./ -type f \( -name '*.r*' -o -name '*.c*' \) -print0 | xargs -0 rm -rf &> log_del.txt How can I do this? And I also see that my log_del.txt file is empty... :-(
It looks like what you really want is to remove all empty directories, recursively. find . -type d -delete -delete processes the directories in child-first order, so that a/b is deleted before a. If a given directory is not empty, find will just display an error and continue.
If the directories remain empty, let rmdir try to remove all of them. It will fail on any directories which have still files. find ./ -type d -exec rmdir --ignore-fail-on-non-empty {} 2>/dev/null \;
See if this serves your requirement: find ./ -type f -name '*.r*' -delete -printf "%h\0" | xargs -0 rmdir If the directory contained any other files, rmdir will fail. So consider below sample file structure: $ find a a/ a/a/ a/a/4 a/b/ a/b/5 a/b/4 a/b/3 a/b/2 a/b/1 $ find a -type f -name '4' -delete -printf "%h\0" | xargs -0 -r rmdir rmdir: failed to remove ‘a/b’: Directory not empty $ find a a a/b a/b/5 a/b/3 a/b/2 a/b/1 If in above example, you want to delete directory b also, you can simply use: $ find ./ -type f -name '*.r*' -printf "%h\0" | xargs -0 rm -rf EDIT: As per the comment, you (OP) wanted that the empty directory tree should also be deleted. These 2 commands should help you then: $ find ./ -type f -name '*.r*' -delete # Delete matching files $ find ./ -empty -type d -delete # Delete tree of empty directories
Recursive erase hidden files
I'm trying to recursive erase all files that begin with "._" (aka mac dot files) on my server using SSH. The files are listed with a ls -a but this won't work: rm -rf ._* I know there's a way. Mind to share? Cheers!
find . -name ._\* -print0 | xargs -0 rm -f
find . -name ._\* -type f -delete Specify that it's files and just call the find-delete on item directly.
find . -name ._\* -exec rm -f {} \; by the way rm -rf is for removing directories recursively
How do I remove all .pyc files from a project?
I've renamed some files in a fairly large project and want to remove the .pyc files they've left behind. I tried the bash script: rm -r *.pyc But that doesn't recurse through the folders as I thought it would. What am I doing wrong?
find . -name "*.pyc" -exec rm -f {} \;
find . -name '*.pyc' -type f -delete Surely the simplest.
Add to your ~/.bashrc: pyclean () { find . -type f -name "*.py[co]" -delete find . -type d -name "__pycache__" -delete } This removes all .pyc and .pyo files, and __pycache__ directories. It's also very fast. Usage is simply: $ cd /path/to/directory $ pyclean
In current version of debian you have pyclean script which is in python-minimal package. Usage is simple: pyclean .
If you're using bash >=4.0 (or zsh) rm **/*.pyc Note that */*.pyc selects all .pyc files in the immediate first-level subdirectories while **/*.pyc recursively scans the whole directory tree. As an example, foo/bar/qux.pyc will be deleted by rm **/*.pyc but not by */*.pyc. The globstar shell options must be enabled. To enable globstar: shopt -s globstar and to check its status: shopt globstar
For windows users: del /S *.pyc
I used to use an alias for that: $ which pycclean pycclean is aliased to `find . -name "*.pyc" | xargs -I {} rm -v "{}"'
find . -name '*.pyc' -print0 | xargs -0 rm The find recursively looks for *.pyc files. The xargs takes that list of names and sends it to rm. The -print0 and the -0 tell the two commands to seperate the filenames with null characters. This allows it to work correctly on file names containing spaces, and even a file name containing a new line. The solution with -exec works, but it spins up a new copy of rm for every file. On a slow system or with a great many files, that'll take too long. You could also add a couple more args: find . -iname '*.pyc' -print0 | xargs -0 --no-run-if-empty rm iname adds case insensitivity, like *.PYC . The no-run-if-empty keeps you from getting an error from rm if you have no such files.
$ find . -name '*.pyc' -delete This is faster than $ find . -name "*.pyc" -exec rm -rf {} \;
Further, people usually want to remove all *.pyc, *.pyo files and __pycache__ directories recursively in the current directory. Command: find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf
Django Extension Note: This answer is very specific to Django project that have already been using Django Extension. python manage.py clean_pyc The implementation can be viewed in its source code.
Just to throw another variant into the mix, you can also use backquotes like this: rm `find . -name *.pyc`
full recursive ll **/**/*.pyc rm **/**/*.pyc
Now there is a package pyclean on PyPI, which is easy to use, and cross-platform. User just need a simple command line to clean all __pycache__ files in current dir: pyclean .
if you don't want .pyc anymore you can use this single line in a terminal: export PYTHONDONTWRITEBYTECODE=1 if you change your mind: unset PYTHONDONTWRITEBYTECODE
First run: find . -type f -name "*.py[c|o]" -exec rm -f {} + Then add: export PYTHONDONTWRITEBYTECODE=1 To ~/.profile
rm -r recurses into directories, but only the directories you give to rm. It will also delete those directories. One solution is: for i in $( find . -name *.pyc ) do rm $i done find will find all *.pyc files recursively in the current directory, and the for loop will iterate through the list of files found, removing each one.
find . -name "*.pyc"|xargs rm -rf
If you want to delete all the .pyc files from the project folder. First, you have cd <path/to/the/folder> then find all the .pyc file and delete. find . -name \*.pyc -delete
You can run find . -name "*.pyc" -type f -delete. But use it with precaution. Run first find . -name "*.pyc" -type f to see exactly which files you will remove. In addition, make sure that -delete is the last argument in your command. If you put it before the -name *.pyc argument, it will delete everything.
To delete all the python compiled files in current directory. find . -name "__pycache__"|xargs rm -rf find . -name "*.pyc"|xargs rm -rf
If you want remove all *.pyc files and __pycache__ directories recursively in the current directory: with python: import os os.popen('find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf') or manually with terminal or cmd: find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf
py3clean works for me! cd /usr/local/lib/python3.9 sudo py3clean -v .
Had to add a few ignore params on M1: pyclean --verbose . --ignore "Library",".Trash"