delete


Delete all files and keep the directory structure

Scenario

You have a complex folder structure and you want to remove all files and at the same time keep all folders intact.

We will present one method, using two variations of it that can achieve the above.
The method uses the GNU find command to find all files and delete them one by one.

Variation A

find . ! -type d -exec rm '{}' \;

This above command will search in the current directory and sub-directories for anything that is not a folder and then it will delete them.

  • find . – Searches in this folder, since we did not define depth, it will search in all sub-folders as well
  • ! -type dtype d instructs find to match all Directories, by adding the ! in front of the instruction it negates the result and instructs find to match anything but the Directories
  • -exec rm '{}' \; – for every result, the command after exec is executed. The filename replaces '{}' so that the results get deleted one by one.

Variation B

find . ! -type d -delete

In this example, we replaced -exec rm '{}' \; with the simpler to remember directive of -delete.


Git: Delete all local branches

The following command will:

  • print all branches that were merged to master
  • then filter out the branch named master and the branch you are currently switched to
  • and finally, it will delete the rest (one branch at a time).
git branch --merged master | grep -v -e "\*" -e "master" | xargs git branch -D

Tip:

To cleanup any remote-tracking references that no longer exist on the remote use the following:

git fetch --prune

Bash: grep: A couple of usefull applications

(How) to delete all empty lines from a file:

cat someFile | grep -v '^$'

(How) to get all numbers that have no sign in front of them (all positive numbers, from a file where on each line there is one number only):

cat someFile | grep ^[0-9]

(How) to extract all negative numbers (from a file where on each line there is one number only):
You can of course replace the minus ‘-‘ character with any other you want to use as a starting character for a line.

cat someFile | grep ^-