Linux make empty file

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

Читайте также:  Команды режима восстановления 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.

Источник

How to create empty file in Linux

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

I use touch file to create an empty file from the command line.

Me thinks that touch command is the easiest way to create new, empty files on Linux or Unix-like systems including macOS.
touch foo bar baz
ls foo bar baz

Источник

4 Ways to Create a Text File in Linux Terminal

In this Linux beginner series, you’ll learn various methods to create a text file in Linux terminal.

If you have used the desktop oriented operating system such as Windows, creating file is a piece of cake. You right click in the file explorer and you would find the option of creating new file.

Things won’t look the same when you are in a command line environment. There is no right click option here. So how do you create a file in Linux then? Let me show you that.

Create file in Linux command line

There are various ways of creating a new file in Linux terminal. I’ll show you the commands one by one. I am using Ubuntu here but creating files in Ubuntu terminal is the same as any other Linux distribution.

1. Create an empty file using touch command

One of the biggest usages of the touch command in Linux is to create a new empty file. The syntax is super simple.

If the file doesn’t exist already, it will create a new empty file. If a file with the same name exists already, it will update the timestamps of the file.

2. Create files using cat command

Another popular way of creating new file is by using the cat command in Linux. The cat command is mostly used for viewing the content of a file but you can use it to create new file as well.

You can write some new text at this time if you want but that’s not necessary. To save and exit, use Ctrl+D terminal shortcut.

If the file with that name already exists and you write new text in it using the cat command, the new lines will be appended at the end of the file.

3. Create new file using echo command

The main use of the echo command is to simply repeat (echo) what you type on the screen. But if you use the redirection with echo, you can create a new file.

To create a new empty file using echo you can use something like this:

The newly created filename.txt file will have the following text: This is a sample text. You can view the file in Linux using cat or other viewing commands.

You are not obliged to put a sample text with echo. You can create an (almost) empty file using the echo command like this:

This will create a new file with just one empty line. You can check the number of lines with wc command.

4. Create a new file using a text editor like Nano or Vim

The last method in this series is the use of a text editor. A terminal-based text editor such as Emacs, Vim or Nano can surely be used for creating a new file in Linux.

Before you use these text editors, you should make sure that you know the basics such as saving an existing from the editor. Unlike the GUI tools, using Ctrl+S in the terminal won’t save the file. It could, in fact, send your terminal into a seemingly frozen state from which you recover using Ctrl+Q.

Let’s say you are going to use Vim editor. Make sure that you are aware of the basic vim commands, and then open a new file with it like this:

What’s your favorite command?

So, I just shared 4 different ways of creating a file in Linux. Personally, I prefer using touch for creating empty file and Vim if I have to edit the file. On a related note, you may want to learn about the file command in Linux that is helpful in determining the actual type of the file.

Which command do you prefer here? Please share your views in the comment section below.

Источник

Как создать пустой файл в Linux?

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

Порывшись на Linux форумах, обнаружил, что вариантов несколько. Предлагаю на выбор 11 способов.

Способ 1

touch — команда Unix, предназначенная для установки времени последнего изменения файла или доступа в текущее время. Также используется для создания пустых файлов.

Способ 2

cat — утилита UNIX, выводящая последовательно указанные файлы (или устройства), таким образом, объединяя их в единый поток. Если вместо имени файла указывается «-», то читается стандартный ввод.

Способ 3

tail — утилита в UNIX, выводящая несколько (по умолчанию 10) последних строк из файла.

Способ 4

date — утилита Unix для работы с системными часами. Выводит текущую дату и время в различных форматах и позволяет устанавливать системное время.

Способ 5

dd — программа Unix, предназначенная как для копирования, так и для конвертации файлов.

Способ 6

Vim — свободный режимный текстовый редактор, созданный на основе более старого vi. Ныне это один из мощнейших текстовых редакторов с полной свободой настройки и автоматизации, и созданным благодаря этому расширениям и надстройкам.

Способ 7

cp — команда Unix в составе GNU Coreutils, предназначенная для копирования файлов из одного в другие каталоги (возможно, с другой файловой системой). Исходный файл остаётся неизменным, имя созданного файла может быть таким же, как у исходного, или измениться.

Способ 8

echo — команда Unix, предназначенная для отображения строки текста. Команда echo — выводит текст (выводит текст на стандартное устройство вывода).

Способ 9

Способ 10

Способ 11

Способ 12

Самый короткий из способов, любезно предоставленный пользователем stam .

Источник

How to create a file in Linux using the bash shell terminal

I am a new Linux system user. How do I create a file in Linux using the bash shell terminal? What is the fastest and easiest way to create a file in a Linux terminal?

Introduction – A file is nothing but a container in a Linux based system for storing information. For example, music stored in a file named foo.mp4. Similarly, my cat’s picture stored in kitten.jpg and so on. This page shows various methods to create a file in Linux using the terminal window.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements Bash shell/terminal on Linux
Est. reading time 3 minutes

How to create a file in Linux from terminal window?

  1. Create an empty text file named foo.txt:
    touch foo.bar
    OR
    > foo.bar
  2. Make a text file on Linux:
    cat > filename.txt
  3. Add data and press CTRL + D to save the filename.txt when using cat on Linux
  4. Run shell command:
    echo ‘This is a test’ > data.txt
  5. Append text to existing file in Linux:
    echo ‘yet another line’ >> data.txt

Let us see some examples for creating a text files on Linux operating systems.

How to create a text file using the cat command

To create a text file named sales.txt, type the following command and then press [Enter] key:
cat > sales.txt
Now type your lines of text. For example:

When done and you need to save and exit, press Ctrl + D to return to the bash shell prompt. To view file use cat or more command/less command:
cat sales.txt
more sales.txt

How to create a file in Linux from terminal window

How to create an empty text file using the touch command

Simply type any one of the following command:
> data.txt
OR
touch test.txt
Verify that empty files are created with the help of ls command:
ls -l data.txt test.txt

Creating a file in Linux using the echo or printf

Let us create a file called quote1.txt using echo command, enter:
echo «While I thought that I was learning how to live, I have been learning how to die.» > quote1.txt
OR use the printf command printf ‘Study nature, love nature, stay close to nature. It will never fail you.\n’ > quote2.txt

Appending data

Use the the >> instead of > to append data to existing file and to avoid overwriting files. The syntax is:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

How to create a file in Linux using joe text editor

JOE is text editor. To create a file called delta.txt, type:
joe -help delta.txt
You will see help menu on screen. Next type something. To save the file and leave joe, by typing ^KX (press CTRL+K+X).

How to create a text file in Linux using vi / vim text editor

The vi / vim is another text editor. To create a file called purchase.txt, type:
vi purchase.txt
OR
vim purchase.txt
Press i to insert new text. To save the file and leave vi, type ESC + : + x (press ESC key, type : followed by x and [enter] key).

Conclusion

You learned various methods that allow you to create text files in a Linux or Unix/macOS terminal window quickly.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Читайте также:  Safari ��� mac os mojave
Оцените статью