How to use xargs rm command to exclude directory

Issue

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:

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

Answered By – Nic3500

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published