- 5 Ways to Empty or Delete a Large File Content in Linux
- 1. Empty File Content by Redirecting to Null
- 2. Empty File Using ‘true’ Command Redirection
- 3. Empty File Using cat/cp/dd utilities with /dev/null
- 4. Empty File Using echo Command
- 5. Empty File Using truncate Command
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- How to clear text in a file?
- 9 Answers 9
- Not the shortest answer but.
- Clear everything except first 10,000 bytes
- How can I delete all lines in a file using vi?
- 14 Answers 14
- Редактируйте фото онлайн бесплатно в редакторе фотографий
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).
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.
Источник
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.
Источник
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.
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
Источник
Редактируйте фото онлайн бесплатно в редакторе фотографий
Теперь не нужно искать фотошоп, платить за услуги редактирования. В интернете это можно сделать самому и бесплатно. Онлайн фото-редактор поможет оригинально, качественно обработать необходимую фотографию.
Онлайн – редактор снимков, который объединил в себе наиболее востребованные и удобные функции редактирования.
Редактор не нужно загружать на компьютер или ноутбук. Пользователю достаточно посетить наш сайт и пользоваться программой в онлайн режиме.
Редактор на русском функционирует оперативно, позволяет оперативно редактировать габаритные снимки. Посетитель может выбрать любое фото с любых источников, в том числе из социальных сетей. После редактирования изображений их можно выставить обратно.
Редактор активно пользуются тысячи посетителей. Мы периодически совершенствуем функции редактора, делаем их эффективнее, увлекательнее, не сложнее в пользовании.
Редактор – многофункциональный редактор, где для обработки фотографий онлайн можно выбрать: разнообразные наклейки; текстуру; тексты; ретушь; оригинальные рамки; с эффектами; коллажи и др.
Редактирование фотографий абсолютно бесплатно, также можно бесплатно пользоваться этим фото в будущем.
Желаете без проблем и качественно отредактировать снимок прямо сейчас? онлайн редактор быстро исправит недостатки, и улучшит качество любого фото!
Человеку не подвластно время. Фотоснимок позволяет сохранить самые дорогие минуты нашей жизни в первозданном облике. Снимок улавливает и передает настроение, эмоции, все тонкие жизненные моменты. С iPhotor для рисования такие воспоминания станут более впечатлительными, яркими и незабываемыми!
Фотография – один из видов искусства. Сам процесс фотографирования простой, но он способен зафиксировать сложные моменты – красивое, хрупкое и быстротечное мгновенье. Это непросто передать с помощью обычных рисунков. Какого бы качества не были фото, редактор iPhotor преобразит даже самое обычные, снятые мобильным или простым фотоаппаратом.
Фотография лучше всего способна передать то, о чем вам хотелось рассказать людям. Фоторедактор iPhotor поможет поделиться с близкими впечатлениями, чувствами, отразит ваше вдохновение.
Возможности Редактора онлайн
Изменение размера, поворот, обрезка
Это самые востребованные операции в фото — редакторе, позволяющие вращать на 90 градусов снимок влево, вправо, по вертикали, горизонтали. Обработка делается оперативно и легко. Для обрезки выбираются границы обрезания фото.
Данное меню позволяет регулировать яркость, ретушь лица, коррекцию теней, светлых участков фото и т.п. Здесь также можно изменить оттенок, насыщенность, увеличить резкость картинок. Изменяя настройки каждого инструмента, можно наблюдать за изменениями в режиме онлайн.
Текст, стикеры, рамки
Графический редактор iPhotor позволяет создавать модные картинки, с прикольными стикерами, оригинальными фото рамками, текстовыми подписями.
Фото — эффекты, фото фильтры
С помощью редактора iPhotor можно бесплатно превратить цветное изображение в черно-белое, или наоборот, сделать виньетирование, наложение фото на фото, эффект пикселизации.
Воспользуйтесь уникальными возможностями фото — редактора онлайн прямо сейчас, сделайте вашу жизнь в реальности и на фото ярче!
Онлайн редактор приукрасит самые дорогие моменты вашей жизни!
Источник