Обнулить все файлы 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.

Читайте также:  How to delete app 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 scan ports linux

Источник

Удалить все содержимое файла (очистить файл) в 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

          Источник

          Стереть содержимое всех текстовых файлов в папке

          А понятие «текстовый» у вас согласно его mime-type? А как вы определяете зулусский язык в Unicode, например?

          4 ответа 4

          что бы «стереть содержимое файлов», можно просто обрезать их размер до нуля. Для этого есть команда truncate —size 0 . Найти все файлы к каталоге (рекурсивно) можно такой командой find . -type f (где точка — текущий каталог).

          Соединяем. Вначале запускаем

          и смотрим на список файлов, что он соответствует требуемому. Если все ок, запускаем такое

          find . -type f -exec truncate --size 0 <> \; 

          запишет в файл (в самое начало) строку нулевой длины, тем самым как бы «сотрёт» содержимое файла.

          аналогичное действие произведёт и такая, например, команда:

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

          $ find -type f -exec truncate -s 0 <> \; 

          это если использовать вариант без перенаправления ввода/вывода (проще говоря — без > ).

          если же требуется использовать перенаправление, придётся вызывать интерпретатор оболочки. с приведёнными выше вариантами:

          $ find -type f -exec sh -c 'cp /dev/null > <>' \; $ find -type f -exec sh -c 'cat /dev/null > <>' \; $ find -type f -exec sh -c ': > <>' \; 

          по поводу текстовых файлов

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

          $ find -type f -exec truncate -s 0 <> \; 

          надо добавить вызов программы grep:

          $ find -type f -exec grep -Iq . <> \; -and -exec truncate -s 0 <> \; 

          аналогично и для других примеров.

          Источник

          Как очистить файл в Linux

          Быстрая очистка содержимого файла (его обнуление) — часто встречающаяся задача для любого программиста, владеющего начальными навыками пользования консоли Linux.

          Мои способы

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

          Способ 1

          Самый простой способ — это использование перенаправление вывода с использованием > :

          Способ 2

          Способ аналогичен предыдущему, но с использованием утилиты echo . Параметр -n запрещает выводить перевод строки (символ новой строки):

          Способ 3

          Магический файл /dev/null — это своего рода Бермудский треугольник вашего компьютера, все, что туда попадает, пропадает бесследно.

          Если при использовании данного варианта вы получили сообщение об ошибке File already exists , можно использовать опцию noclobber :

          Способ 4

          Суть его заключается в копировании магического файла в очищаемый вами:

          Способ 5

          Можно также использовать утилиту truncate , которая уменьшаяет или увеличивает размер файла:

          Способ 6

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

          Русский разработчик со стажем. Работаю с PHP, ООП, JavaScript, Git, WordPress, Joomla, Drupal. Оптимизирую сайты под Google Page Speed, настраиваю импорты для больших магазинов на WooCommerce + WP All Import. Пишу плагины на заказ. Все мои услуги. Веду блог о разработке, дайджест в телеграмме и в ВК. Вы всегда можете нанять меня.

          Источник

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