How to Delete a File in Linux?
Need to clear some space on your Linux system? It’s easier than you might think! With a simple command, you can swiftly delete any file. But what’s the right way to do it without causing any hiccups? Let’s find out!
In Linux, we make use of the rm command to remove unnecessary files from your system. Whenever we make use of the rm command, it removes the entries of the specified file(s) from the system. It can be used to delete:
- Specific file
- Group of files
- Selected file(s) with a specific extension(s)
Let’s understand how to delete file in Linux.
The syntax to delete the file(s) from a Linux system is as below:
- Syntax: For deleting a single file
rm <file_name>
- Syntax: For deleting multiple files.
rm <file_name_1> <file_name_2>….<file_name_n>
- Syntax: For deleting file(s) with specific extensions(s):
rm *.<file_extension>
Now let’s take a look at a few examples. For the sake of example, we will be deleting files from a directory that has the following files.
In the test directory shown above, we currently have 5 different files. Now let’s jump into the examples.
Note: The ls command is used for listing all the files and directories within a directory.
You can also explore: Top 60 Linux Interview Questions and Answers (2022)
Deleting a Specific File in Linux:
Example: Here we will use the rm command to delete the file test_file_1.
rm test_file_1
Output:
As we can see in the above output, the test_file_1 gets deleted once we use the rm command on it.
You can also explore: Learn Basic Linux Commands (With Syntax)
Best-suited Linux courses for you
Learn Linux with these high-rated online courses
Deleting Multiple Files in Linux:
Example: Here we will use the rm command to delete the files namely, test_file_2 and test_file_3.
rm test_file_2 test_file_3
Output:
Deleting File(s) with Specific Extension(s) in Linux:
For the purpose of demonstration, we have added a couple of python files , pdf files, and text files to the test directory that we are currently on. Currently, we have the following files in the test directory:
Example 1: Here we will delete all the files with the .pdf extension from the directory.
rm *.pdf
Output:
As you can observe from the above output, all files with the .pdf (ie, test_file_8.pdf and test_file_9.pdf) extensions are deleted.
Conclusion:
In this article, we have covered how to delete file in a Linux and explored the use cases of the rm command. We have also managed to cover the following concepts in this article:
- Deleting specific files in Linux
- Deleting group of files in Linux.
- Deleting files with specific extensions in Linux.
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio