Linux delete all contents file

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.

Читайте также:  Путь до php ini 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.

Источник

How to Delete all Text in a File Using Vi/Vim Editor

Vim is a great tool for editing text or configuration files in Linux. One of the lesser-known Vim tricks is clearing or deleting all text or lines in a file. Although, this is not a frequently used operation, its a good practice to know or learn it.

Читайте также:  What is lsmod in linux

In this article, we will describe steps on how to delete, remove or clear all text in a file using a Vim editor in different vim modes.

The first option is to remove, clear or delete the all lines in a file in the normal mode (note that Vim starts in “normal” mode by default). Immediately after opening a file, type “gg” to move the cursor to the first line of the file, assuming it is not already there. Then type dG to delete all the lines or text in it.

Delete Complete Text in Vi Editor

If Vim is in another mode, for example, insert mode, you can access normal mode by pressing Esc or C-[> .

Alternatively, you can also clear all lines or text in Vi/Vim in command mode by running the following command.

Delete Text in Vi Editor

Last but not least, here is a list of Vim articles that you will find useful:

In this article, we have explained how to clear or delete all lines or text in a file using Vi/Vim editor. Remember to share your thoughts with us or ask questions using the comment form below.

Источник

Удалить все содержимое файла (очистить файл) в Unix/Linux

Хочу описать в своей статье «Удалить все содержимое файла в Unix/Linux» как можно очистить содержимое файла. Некоторые скажут что это банально, взял удалил файл и создал заново, делов то. Но иногда это не проще и не выход.

Тем более для общего развития, та кому то и пригодиться. Я вот, например, не все методы знал.

1. Если вы хотите очистить содержимое файла вы можете просто удалить файл и создать его заново:

$ rm -rf /home/captain/file_for_delete.txt

2. Существуют и другие методы очистки файла, например методом «echo».

Чтобы очистить свой файл, просто введите следующую команду. Я использую свой php_error.log файл, например.

# echo -n > /home/captain/some_file_for_clear.txt

3. Можно удалить содержимое файла с помощью редакторов, например VI/VIM. Открываем файл, я открою его vim:

# vim /home/captain/some_file_for_clear.txt

Когда открылся редактор, нажимаем «dG» и чтобы сохранить, используем сначала «:» и наживаем «wq» после чего нажимаем энтер.

PS: Команды нужно использовать без кавычек.

4. Используем null для очистки файла:

# cat /dev/null > /home/captain/file_clean.sh
# cp /dev/null > /home/captain/file_clean.sh

5. Еще 1 интересная команда для очистки файла:

6. С помощью текстового редактора SED:

Тема «Удалить все содержимое файла (очистить файл) в Unix/Linux» завершена.

One thought on “ Удалить все содержимое файла (очистить файл) в Unix/Linux ”

Добавить комментарий Отменить ответ

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.

Рубрики

  • Arch Linux (167)
  • Commands (36)
  • Debian’s (635)
    • Administration tools Ubuntu (37)
    • Backups Debian’s (7)
    • Database в Ubuntu (58)
    • Games (игры) (1)
    • Monitoring в Debian и Ubuntu (49)
    • Virtualization в Ubuntu / Debian/ Linux Mint (41)
      • Docker (22)
      • Kubernetes (6)
      • KVM (4)
      • OpenVZ (3)
      • Vagrant (5)
      • VirtualBox (6)
      • ArgoCD (1)
      • Concourse (1)
      • Gitlab (1)
      • Jenkinks (4)
      • Spinnaker (1)
      • Apache (32)
      • Cherokee (1)
      • FTP-services (5)
      • Lighttpd (1)
      • Nginx (26)
      • PHP (27)
      • Proxy для Debian’s (2)
      • Tomcat (4)
      • Панели управления в Ubuntu/Debian/Mint (24)
      • Установка и настройка почты на Ubuntu/Debian (12)
      • Хранилища (clouds) (2)
      • Administration tools freeBSD (19)
      • Database во FreeBSD (52)
      • Monitoring во freeBSD (37)
      • Virtualization во FreeBSD (22)
      • VoIP (1)
      • Установка Web сервисов (91)
      • Установка и настройка почты (6)
      • Установка из ports (пакетов) (19)
      • Установка из sorce code (исходников) (23)
      • Непрерывная интеграция (CI) (27)
      • Database в MacOS (36)
      • Monitoring в Mac OS (31)
      • Security (безопасность) (12)
      • Virtualization в Mac OS (30)
        • Docker (19)
        • Kubernetes (6)
        • Vagrant (5)
        • VirtualBox (5)
        • ArgoCD (1)
        • CircleCI (1)
        • Concourse (1)
        • Gitlab (1)
        • Jenkinks (4)
        • Spinnaker (1)
        • Administration tools CentOS (49)
        • Backups RPM’s (4)
        • Database в CentOS (68)
        • Monitoring в CentOS (67)
        • Virtualization в CentOS/ Red Hat/ Fedora (42)
          • Docker (23)
          • Kubernetes (6)
          • KVM (5)
          • OpenVZ (2)
          • Vagrant (5)
          • VirtualBox (6)
          • VMWare (3)
          • ArgoCD (1)
          • Concourse (1)
          • Gitlab (1)
          • Jenkinks (4)
          • Spinnaker (1)
          • Apache (35)
          • Cherokee (1)
          • DNS (3)
          • FTP (10)
          • Nginx (33)
          • PHP (34)
          • Proxy для RedHat’s (2)
          • Tomcat (2)
          • Voice (2)
          • Панели управления в CentOS/Red Hat/Fedora (27)
          • Прокси сервер на CentOS/RHEL/Fedora (4)
          • Установка и настройка почты на CentOS/RHEL/Fedora (14)
          • Хранилища (clouds) (1)

          соц сети

          Unix-Linux- в примерах

          Unix-Linux- в примерах

          Unix-Linux- в примерах

          Архив новостей

          Свежие записи

          Свежие комментарии

          • Глеб к записи Установка Adobe Flash Player в Debian/Ubuntu/Mint
          • Максим к записи Заблокировать User Agents используя Nginx
          • Денис к записи Как включить EPEL репозиторий на CentOS
          • Гость к записи Закомментировать/Раскомментировать строки vi/vim в Unix/Linux
          • Sergey к записи Установка и настройка OpenVPN сервера на Debian/Ubuntu/Linux Mint

          Источник

          How to delete the contents of all the files in a directory

          Under /tmp/REPORTS I have a hundred files. What I want to do is erase the contents of each file in /tmp/REPORTS (not delete them). So I tried the following, but I get this error:

          cp /dev/null /tmp/REPORTS/* cp: Target /tmp/REPORTS/….. must be a directory Usage: cp [-f] [-i] [-p] [-@] f1 f2 cp [-f] [-i] [-p] [-@] f1 . fn d1 cp -r|-R [-H|-L|-P] [-f] [-i] [-p] [-@] d1 . dn-1 dn 

          4 Answers 4

          Assuming that you mean you want to truncate the contents of each file, you can do this:

          for file in /tmp/REPORTS/*; do > "$file"; done 

          This will clear the contents of each file in the directory.

          As gniourf_gniourf has suggested in the comments above, there is a GNU tool truncate that can do the job for you as well:

          truncate --size 0 /tmp/REPORTS/* 

          This will possibly be quicker than looping through the files manually.

          ok , btw in many linux/solaris the command truncate not defined , so I will choose the first option , and +1 for you

          Actually, it would only clear the first byte of the file. OP asked to overwrite the file’s contents with 0’s.

          For truncate , the manpage hints that blocks which were part of the file before are still present on the filesystem, containing the unerased data.

          The question appears to be asking for what is termed a «secure erase».

          While you cannot cp /dev/null , you could get the effect you are asking about using dd . Here is a script to illustrate:

          #!/bin/sh for name in $* do test -h "$name" && continue test -f "$name" || continue blocks=`ls -s "$name" | awk ''` dd if=/dev/zero of="$name" count=$blocks done 
          • checks to ensure that the parameter is a regular file.
          • then it asks for the number of blocks for the file.
          • finally, it uses dd to copy 0’s from the special device /dev/zero .

          This relies on dd and ls having the same notion of blocksize (which appears to be the case). It also assumes that the filesystem does not reallocate blocks for a given file, i.e., that they can be reliably overwritten in-place. If you want a better guarantee, there are other solutions, e.g., this discussion of Secure Erase in UNIX

          Источник

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