Linux clear from files

Linux Delete All Files In Directory Using Command Line

Linux Delete All Files In Directory

The procedure to remove all files from a directory:

  1. Open the terminal application
  2. To delete everything in a directory run: rm /path/to/dir/*
  3. To remove all sub-directories and files: rm -r /path/to/dir/*

Let us see some examples of rm command to delete all files in a directory when using Linux operating systems.

How to remove all the files in a directory?

Suppose you have a directory called /home/vivek/data/. To list files type the ls command:
$ ls

Understanding rm command option that deleted all files in a directory

  • -r : Remove directories and their contents recursively.
  • -f : Force option. In other words, ignore nonexistent files and arguments, never prompt. Dangerous option. Be careful.
  • -v : Verbose option. Show what rm is doing on screen.

Deleting hidden vs non-hidden files

In Linux, any file or directory that starts with a dot character called a dot file. It is to be treated as hidden file. To see hidden files pass the -a to the ls command:
ls
ls -a
ls -la
To remove all files except hidden files in a directory use:
rm /path/to/dir/*
rm -rf /path/to/dir/*
rm *
In this example, delete all files including hidden files, run:
rm -rf /path/to/dir1/<*,.*>
rm -rfv /path/to/dir1/

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Bash remove all files from a directory including hidden files using the dotglob option

If the dotglob option set, bash includes filenames beginning with a ‘.’ in the results of pathname expansion. In other words, turn on this option to delete hidden files:

See GNU/bash man page for the shopt command online here:
man bash
help shopt

Linux Remove All Files In Directory

As I said earlier one can use the unlink command too. The syntax is:
unlink filename
For example, delete file named foo.txt in the current working directory, enter:
unlink foo.txt
It can only delete a single file at a time. You can not pass multiple files or use wildcards such as *. Therefore, I strongly recommend you use the rm command as discussed above.

Conclusion

In this quick tutorial, you learned how to remove or delete all the files in a directory using the rm command. Linux offers a few more options to find and delete files. Please see the following tutorials:

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

5 Ways to Empty or Delete a Large File Content in Linux

Occasionally, while dealing with files in Linux terminal, you may want to clear the content of a file without necessarily opening it using any Linux command line editors. How can this be achieved? In this article, we will go through several different ways of emptying file content with the help of some useful commands.

Читайте также:  Звуковые схемы windows это

Caution: Before we proceed to looking at the various ways, note that because in Linux everything is a file, you must always make sure that the file(s) you are emptying are not important user or system files. Clearing the content of a critical system or configuration file could lead to a fatal application/system error or failure.

With that said, below are means of clearing file content from the command line.

Important: For the purpose of this article, we’ve used file access.log in the following examples.

1. Empty File Content by Redirecting to Null

A easiest way to empty or blank a file content using shell redirect null (non-existent object) to the file as below:

Empty Large File Using Null Redirect in Linux

2. Empty File Using ‘true’ Command Redirection

Here we will use a symbol : is a shell built-in command that is essence equivalent to the true command and it can be used as a no-op (no operation).

Another method is to redirect the output of : or true built-in command to the file like so:

Empty Large File Using Linux Commands

3. Empty File Using cat/cp/dd utilities with /dev/null

In Linux, the null device is basically utilized for discarding of unwanted output streams of a process, or else as a suitable empty file for input streams. This is normally done by redirection mechanism.

And the /dev/null device file is therefore a special file that writes-off (removes) any input sent to it or its output is same as that of an empty file.

Additionally, you can empty contents of a file by redirecting output of /dev/null to it (file) as input using cat command:

Empty File Using cat Command

Next, we will use cp command to blank a file content as shown.

Empty File Content Using cp Command

In the following command, if means the input file and of refers to the output file.

Empty File Content Using dd Command

4. Empty File Using echo Command

Here, you can use an echo command with an empty string and redirect it to the file as follows:

Empty File Using echo Command

Note: You should keep in mind that an empty string is not the same as null. A string is already an object much as it may be empty while null simply means non-existence of an object.

For this reason, when you redirect the out of the echo command above into the file, and view the file contents using the cat command, is prints an empty line (empty string).

To send a null output to the file, use the flag -n which tells echo to not output the trailing newline that leads to the empty line produced in the previous command.

Empty File Using Null Redirect

5. Empty File Using truncate Command

The truncate command helps to shrink or extend the size of a file to a defined size.

You can employ it with the -s option that specifies the file size. To empty a file content, use a size of 0 (zero) as in the next command:

Truncate File Content in Linux

That’s it for now, in this article we have covered multiple methods of clearing or emptying file content using simple command line utilities and shell redirection mechanism.

These are not probably the only available practical ways of doing this, so you can also tell us about any other methods not mentioned in this guide via the feedback section below.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

Читайте также:  Последняя ось mac os

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

How to clear text in a file?

How to clear text that existed in a text file without opening it?

I mean for example I have a file as hello.txt with some text data in it, and how can I clear the total text in that file without opening it?

By this, I mean not using any editor like nano, Gedit, etc.

9 Answers 9

Just open your terminal with CTRL + ALT + T and type as

that’s it, your data in that file will be cleared with out opening it even .

The easiest way is to truncate a file is to redirect the output of the shell no-op command ( : ) to the file you want to erase.

I have to do this all the time with log files. The easiest way I have found is with the following command:

This deletes allo of the content of the file, and leaves you with an empty file without having to open it in an editor, select text, any of that stuff. More specifically what it does is to replace the contents of the file with the contents of «/dev/null», or nothing. It’s pretty slick, actually.

The only caveat is that the user you are currently logged in as must have write permission to said file.

I am also going to use redirection like rajagenupula’s answer. But there is a little more flexibility. Open a terminal and type,

And press Ctrl + C . It will wipe out the previous file. If you want upto this much it is fine.

If you wish you can do something more after wiping the file. In this way not only you can wipe a file without opening but also you can write a few lines with proper formatting in the file. Say you wish to write «Ubuntu is the best OS» after wiping the file, just do

Then press Ctrl + C . Now the previous file is wiped out. At the same time words are there in two lines as I put them.

See the example:

If a file was created with the name hello.txt and was provided with some texts then the below command in terminal ctrl + alt + t will remove all the text in the hello.txt file,

Not the shortest answer but.

This answer is based on another from Super User. Although not the shortest bash command, truncate is the most readable for average newbies:

Parameters used with truncate command here:

  • «-s» set the size
  • «0» size will be zero

Clear everything except first 10,000 bytes

An advantage of truncate is you can specify how much to keep, not just zero:

. will truncate everything after the first 10,000 bytes. This could be useful if a program went crazy and dumped many Megabytes of data into a small log file:

  • Run the truncate command for a reasonable larger normal size of 10K
  • Open the file with your text editor and press End
  • Highlight and PgUp to delete the remaining bytes that don’t belong (usually recognizable by ASCII garbage characters).

Another approach — cp the /dev/null to the file

Why does this work and how does this work ? The testFile.txt will be opened with O_WRONLY|O_TRUNC flags, which means if the file exists — it will be truncated, which means contents discarded and size set to zero. This is the same flag with which > operator in shell opens the file on the right of that operator.

Next, cp will attempt to read from /dev/null and after reading 0 bytes will simply close both files, thus leaving testFile.txt truncated and contents effectively deleted.

Knowing that, we could in theory use anything that allows us to open a file with O_TRUNC . For instance this:

Small difference here is that dd won’t perform any read() at all. Big plus of this dd version is that it is POSIXly portable. The dd specifications state:

If the seek= expr conversion is not also specified, the output file shall be truncated before the copy begins if an explicit of= file operand is specified, unless conv= notrunc is specified.

Источник

Читайте также:  Восстановительный образ windows 10

How To Clear .Cache Folders and Free Up Space On Your Linux PC

Clean up your cache in a few easy steps!

GNU/Linux has implemented efficient storage management for its users. But have you noticed your Linux system running out of space, filled with unused packages you installed months or years ago? How do find them and remove them? Here are a few valuable tips!

Cache File Location

Cache files are stored in /home/username/.cache which mostly consists of your browser’s data, IDE’s (if you use any ) and other software. Each user has its own data and this can build up exponentially . In order to clear it all it’s recommended to have Disk usage analyzer installed.

Disk Usage Analyzer

Disk Usage Analyzer, formerly known as Baobab, is a graphical disk usage analyzer for the GNOME desktop environment. It was part of gnome-utils, but has been a standalone application since GNOME 3.4.

The software gives the user a graphical representation of a disk drive’s contents. The interface allows for selection of specific parts of filesystem so a single folder, the entire filesystem, and even remote folders and filesystems can be scanned and listed at the folder level.

The graphical representation can be switched between a ‘Rings’ chart and a ‘Treemap’ chart to better suit the content being viewed.

Installation

If you don’t already have Disk Usage Analyzer installed, you first need to install the baobab package:

Clear Cache files and folders

Click on home for your user data .

Click on your second disk i.e Vostro-14-3468 as shown in the image below .

Note: Names will be different on your own computer.

Here, the other disks shown as New Volume / 262 GB volume are formatted disks for a dual boot system, in my case Ubuntu 20.10 and Windows 10.

As you click on it, the Disk Usage Analyzer will start to scan your directory for files and folders. Be patient and allow it to finish. After Disk Usage Analyzer is done scanning your Linux PC for files it shows the live illustration of Linux disk usage as the form of a pie chart.

To see updated changes in your filesystem, you’ll need to refresh the scan as it won’t track these storage changes “live.”

Look in the folder tree structure for .cache, and click on it .

Once you click on the .cache folder, the disk usage analyzer will show you the space it’s consuming graphically on the right side .

  • Find the sub folders inside it which you wish to delete .
  • Right-click each one
  • Select Move to trash / bin
  • Now empty your trash / bin

And you are done!

Do not worry about deleting these folders. It is totally safe and the software will recreate them if and when it needs to.

WARNING!

Do not delete anything from your usr and var directories. usr is used for “user programs”. Usually your package manager installs all the binaries, shared files etc. from all programs here (except config files, which go to /etc).

You can check /usr/bin for binaries, /usr/share for shared files (media, etc), /usr/share/doc for documentation.

There is also an /opt folder, where there are “other” binary programs or programs installed from sources other than the default package manager. Some programs like that (usually compiled) also go to usr/local

/var is usually used for log files, ‘temporary’ files (like mail spool, printer spool, etc), databases, and all other data not tied to a specific user.

Logs are usually in /var/log databases in var/lib (mysql — var/lib/mysql ), etc.

If you liked this article, please follow the author on medium !

Источник

Оцените статью