Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use xargs rm command to exclude directory

I have to write a shell script so that it should remove all the files except test.txt
When I run the script, it says Removal of Source file failed because dev_data is a directory.

ls | grep -v 'test.txt' | xargs rm

I want to write a shell script so that if there is a directory in the below path, it should skip the directory. The script should remove only the files inside the directory – dev_data

Error Log is given below:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ig_dir.sh process starts at: 
Wed Nov 2 08:08:09 IST 2022

tar: Removing leading `/' from member names
/alb/albt_shard/alb1/path1/path2/alb1/sub/alby/
/alb/albt_shard/alb1/path1/path2/alb1/sub/alby/dev_data/
/alb/albt_shard/alb1/path1/path2/alb1/sub/alby/dev_data/list_file.place.txt
rm: cannot remove ‘dev_data’: Is a directory
ig_dir.sh: Removal of Source file failed

This is how I’m passing the parameter — sh -x ig_dir.sh.sh /alb/albt_shard/alb1/path1/path2/alb1/sub/alby.. So when I pass this as argument to the script, it checks for the directory under alby and gives — rm: cannot remove ‘dev_data’: Is a directory

>Solution :

"The script should remove only the files inside the directory – dev_data"

find dev_data -maxdepth 1 -type f ! -name test.txt -delete
  • Specify your starting point as dev_data
  • -maxdepth 1 ensures it will not descend in dev_data sub-directories
  • ! -name test.txt ignores files named test.txt (the ! is "not")
  • you can add -print to get a list of deleted files
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading