Очистка содержимого файла linux

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.

What do you mean by ‘opening’ a file? In all the answers given so far the file will still be opened for writing by the shell. In the end the shell is just a program like any other.

Hus787 I have not typed from getting there if you think so else I welcome your interest in my question.

I agree with Jeff’s comment. I too have opinion* that the file stream has to be opened to write to it, whether you use any text editors, or redirection. (*appreciate anybody suggedting links to help with the matter)

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 .

enter image description here

@souravc John is correct, the file will be open. Shell opens a file for redirection > with flags O_WRITE|O_TRUNC . In fact, this is stated in the bash manual explicitly under Redirecting Output section: «If the file does not exist it is created; if it does exist it is truncated to zero size.»

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.

Its probably not the easiest (relative to just > ) but the fastest for sure..i wonder why it has not been mentioned in any of the answers of this highly viewed question..here, take +1..

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

cat > hello.txt Ubuntu is the best OS 

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.

Читайте также:  Метка файловой системы linux

enter image description here

hey thank you for answering. so little but work to be done right after that also & but still interesting .+1

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:

$ echo Hello > Hello.txt $ echo World! >> Hello.txt $ cat Hello.txt Hello World! $ truncate -s 0 Hello.txt $ ll Hello.txt -rw-rw-r-- 1 rick rick 0 Mar 20 17:32 Hello.txt 

Parameters used with truncate command here:

Clear everything except first 10,000 bytes

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

$ truncate -s 10000 Hello.txt 

. 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

xieerqi:$ cat testFile.txt Filesystem 1K-blocks Used Available Use% Mounted on /dev/sda1 115247656 83100492 26269816 76% / none 4 0 4 0% /sys/fs/cgroup udev 2914492 4 2914488 1% /dev tmpfs 585216 1152 584064 1% /run none 5120 0 5120 0% /run/lock none 2926072 98096 2827976 4% /run/shm none 102400 76 102324 1% /run/user xieerqi:$ cp /dev/null testFile.txt xieerqi:$ cat testFile.txt xieerqi:$ 

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.

By contrast cp /dev/null testFile.txt isn’t necessarily portable, since POSIX specifications for cp cover what happens only if source_file is non-regular and when -r / -R flags are specified (big thanks to Stephen Kitt for pointing this out), but not what happens when -r or -R are omitted, which is the case here. However it appears at least GNU cp defaults to using rule 3 in the same spec, which is truncating the existing file without changing its type.

Источник

5 способов очистить или удалить содержимое большого файла в Linux

Иногда при работе с файлами в терминале Linux вам может понадобиться очистить содержимое файла, не обязательно открывая его с помощью каких-либо редакторов командной строки Linux. Как этого добиться? В этой статье мы рассмотрим несколько различных способов очистки содержимого файла с помощью некоторых полезных команд.

Читайте также:  Отличие linux mint от debian

Внимание: прежде чем мы перейдем к рассмотрению различных способов, обратите внимание, что, поскольку в Linux все является файлом, вы всегда должны убедиться, что файл(ы) вы очищаете не важные пользовательские или системные файлы. Очистка содержимого критической системы или файла конфигурации может привести к фатальной ошибке или сбою приложения/системы.

С учетом сказанного ниже приведены способы очистки содержимого файла из командной строки.

Важно. В целях этой статьи мы использовали файл access.log в следующих примерах.

1. Пустое содержимое файла путем перенаправления на Null

Самый простой способ очистить содержимое файла с помощью перенаправления оболочки null (несуществующий объект) в файл, как показано ниже:

2. Пустой файл с использованием «настоящего» перенаправления команд

Здесь мы будем использовать символ : — это встроенная команда оболочки, которая по сути эквивалентна команде true и может использоваться как неоперативная (без операции) .

Другой способ — перенаправить вывод встроенной команды : или true в файл следующим образом:

# : > access.log OR # true > access.log

3. Пустой файл с помощью утилиты cat/cp/dd с /dev/null

В Linux устройство null в основном используется для отбрасывания нежелательных выходных потоков процесса или в качестве подходящего пустого файла для входных потоков. Обычно это делается с помощью механизма перенаправления.

Таким образом, файл устройства /dev/null является специальным файлом, который списывает (удаляет) любой отправленный ему ввод или его вывод такой же, как у пустого файла.

Кроме того, вы можете очистить содержимое файла, перенаправив вывод /dev/null в него (файл) в качестве ввода с помощью команды cat:

Далее мы будем использовать команду cp для очистки содержимого файла, как показано на рисунке.

В следующей команде if означает входной файл, а of — выходной файл.

4. Очистить файл с помощью команды echo

Здесь вы можете использовать команду echo с пустой строкой и перенаправить ее в файл следующим образом:

# echo "" > access.log OR # echo > access.log

Примечание. Следует помнить, что пустая строка не равно нулю. Строка уже является объектом, поскольку она может быть пустой, а нуль просто означает отсутствие объекта.

По этой причине, когда вы перенаправляете команду out of the cat, печатается пустая строка (пустая строка).

Чтобы отправить вывод null в файл, используйте флаг -n , который указывает echo не выводить завершающую новую строку, которая ведет к пустой строке, созданной в предыдущей команде.

5. Очистить файл с помощью команды truncate

Команда truncate помогает уменьшить или увеличить размер файла до определенного размера.

Вы можете использовать его с опцией -s , которая определяет размер файла. Чтобы очистить содержимое файла, используйте размер 0 (ноль), как в следующей команде:

На данный момент это все, в этой статье мы рассмотрели несколько методов очистки или очистки содержимого файла с использованием простых утилит командной строки и механизма перенаправления оболочки.

Вероятно, это не единственные доступные практические способы сделать это, поэтому вы также можете сообщить нам о любых других методах, не упомянутых в этом руководстве, в разделе обратной связи ниже.

Источник

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.

Читайте также:  One sided printing linux

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:

# : > access.log OR # true > access.log

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:

# echo "" > access.log OR # echo > access.log

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.

Источник

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