Linux clear file content

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.

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).

Читайте также:  Какие основные характеристики имеет ос ms windows

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.

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.

Источник

Редактируйте фото онлайн бесплатно в редакторе фотографий

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

Онлайн – редактор снимков, который объединил в себе наиболее востребованные и удобные функции редактирования.

Редактор не нужно загружать на компьютер или ноутбук. Пользователю достаточно посетить наш сайт и пользоваться программой в онлайн режиме.

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

Редактор активно пользуются тысячи посетителей. Мы периодически совершенствуем функции редактора, делаем их эффективнее, увлекательнее, не сложнее в пользовании.

Редактор – многофункциональный редактор, где для обработки фотографий онлайн можно выбрать: разнообразные наклейки; текстуру; тексты; ретушь; оригинальные рамки; с эффектами; коллажи и др.

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

Желаете без проблем и качественно отредактировать снимок прямо сейчас? онлайн редактор быстро исправит недостатки, и улучшит качество любого фото!

Человеку не подвластно время. Фотоснимок позволяет сохранить самые дорогие минуты нашей жизни в первозданном облике. Снимок улавливает и передает настроение, эмоции, все тонкие жизненные моменты. С iPhotor для рисования такие воспоминания станут более впечатлительными, яркими и незабываемыми!

Фотография – один из видов искусства. Сам процесс фотографирования простой, но он способен зафиксировать сложные моменты – красивое, хрупкое и быстротечное мгновенье. Это непросто передать с помощью обычных рисунков. Какого бы качества не были фото, редактор iPhotor преобразит даже самое обычные, снятые мобильным или простым фотоаппаратом.

Фотография лучше всего способна передать то, о чем вам хотелось рассказать людям. Фоторедактор iPhotor поможет поделиться с близкими впечатлениями, чувствами, отразит ваше вдохновение.

Читайте также:  Colin mcrae rally 2005 windows 10

Возможности Редактора онлайн

Изменение размера, поворот, обрезка

Это самые востребованные операции в фото — редакторе, позволяющие вращать на 90 градусов снимок влево, вправо, по вертикали, горизонтали. Обработка делается оперативно и легко. Для обрезки выбираются границы обрезания фото.

Данное меню позволяет регулировать яркость, ретушь лица, коррекцию теней, светлых участков фото и т.п. Здесь также можно изменить оттенок, насыщенность, увеличить резкость картинок. Изменяя настройки каждого инструмента, можно наблюдать за изменениями в режиме онлайн.

Текст, стикеры, рамки

Графический редактор iPhotor позволяет создавать модные картинки, с прикольными стикерами, оригинальными фото рамками, текстовыми подписями.

Фото — эффекты, фото фильтры

С помощью редактора iPhotor можно бесплатно превратить цветное изображение в черно-белое, или наоборот, сделать виньетирование, наложение фото на фото, эффект пикселизации.

Воспользуйтесь уникальными возможностями фото — редактора онлайн прямо сейчас, сделайте вашу жизнь в реальности и на фото ярче!

Онлайн редактор приукрасит самые дорогие моменты вашей жизни!

Источник

How to remove all files from a directory?

The closest I’ve gotten is

but that doesn’t work for files that don’t have an extension.

9 Answers 9

Linux does not use extensions. It is up to the creator of the file to decide whether the name should have an extension. Linux looks at the first few bytes to figure out what kind of file it is dealing with.

To remove all non-hidden files* in a directory use:

However, this will show an error for each sub-directory, because in this mode it is only allowed to delete files.

To remove all non-hidden files and sub-directories (along with all of their contents) in a directory use:

* Hidden files and directories are those whose names start with . (dot) character, e.g.: .hidden-file or .hidden-directory/ . Note that, in Bash, if the dotglob option (which is off by default) is set, rm will act on hidden files too, because they will be included when * is expanded by the shell to provide the list of filename arguments.

To remove a folder with all its contents (including all interior folders):

To remove all the contents of the folder (including all interior folders) but not the folder itself:

or, if you want to make sure that hidden files/directories are also removed:

To remove all the «files» from inside a folder(not removing interior folders):

Warning: if you have spaces in your path, make sure to always use quotes.

is equivalent to 2 separate rm -rf calls:

To avoid this issue, you can use ‘ single-quotes ‘ (prevents all expansions, even of shell variables) or » double-quotes » (allows expansion of shell variables, but prevents other expansions):

  • rm — stands for remove
  • -f — stands for force which is helpful when you don’t want to be asked/prompted if you want to remove an archive, for example.
  • -r — stands for recursive which means that you want to go recursively down every folder and remove everything.

Источник

How can I delete all lines in a file using vi?

How can I delete all lines in a file using vi?

At moment I do that using something like this to remove all lines in a file:

How can I delete all lines using vi ?

Note: Using dd is not a good option. There can be many lines.

14 Answers 14

to delete all lines.

Читайте также:  Puppy linux apt get

The : introduces a command (and moves the cursor to the bottom).
The 1,$ is an indication of which lines the following command ( d ) should work on. In this case the range from line one to the last line (indicated by $ , so you don’t need to know the number of lines in the document).
The final d stands for delete the indicated lines.

There is a shorter form ( :%d ) but I find myself never using it. The :1,$d can be more easily «adapted» to e.g. :4,$-2d leaving only the first 3 and last 2 lines, deleting the rest.

  • : tells vi to go in command mode
  • % means all the lines
  • d : delete

On the command line,

What is the problem with dd?

  • /dev/null is a special 0 byte file
  • if is the input file
  • of is the ouput file

I’d recommend that you just do this (should work in any POSIX-compliant shell):

If you really want to do it with vi, you can do:

  • 1G (go to first line)
  • dG (delete to last line)

If your cursor is on the first line (if not, type: gg or 1G ), then you can just use dG . It will delete all lines from the current line to the end of file. So to make sure that you’ll delete all the lines from the file, you may mix both together, which would be: ggdG (while in command mode).

Or %d in Ex mode, command-line example: vim +%d foo.bar .

I’m a lazy dude, and I like to keep it simple. ggdG is five keystrokes including Shift

gg goes to the first line in the file, d is the start of the d elete verb and G is the movement to go to the bottom of the file. Verbosely, it’s go to the beginning of the file and delete everything until the end of the tile.

Go to the beginning of the file and press d G .

I always use ggVG

  • gg jumps to the start of the current editing file
  • V (capitalized v) will select the current line. In this case the first line of the current editing file
  • G (capitalized g) will jump to the end of the file. In this case, since I selected the first line, G will select the whole text in this file.

Then you can simply press d or x to delete all the lines.

note that in your question, echo > test.txt creates a file with a single line break in it, not an empty file.

From the shell, consider using echo -n > test.txt or : > test.txt .

While I’d generally use a vi editing command (I use ggdG ), you can also call out to the shell with a reference to the current file like so:

It’s nearly as concise as ggdG , but harder to type, and you also have to confirm that you want to reload the modified file, so I don’t particularly recommend it in this case, but knowing how to use shell commands from vi like this is useful.

breaking it down:

  • : initiate a vi command
  • ! initate a shell command
  • : this is a shell builtin command with empty output
  • > redirect the output
  • % vi substitutes this with the name of the current file

The suggested :1,$d is also a good one of course, and just while I’m at it there’s also 1GdG

Источник

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