- 7 Ways to Create a File in Linux Terminal
- 1) Create a file with touch command
- 2) Create a file with cat command
- 3) Create a file with echo command
- 4) Create a file with printf command
- 5) Create a file with nano text editor
- 6) Create a file with vi text editor
- 7) Create a file with vim text editor
- Conclusion
- Команда cat Linux
- Команда cat
- Использование cat в Linux
- Выводы
- The Cat Command in Linux – How to Create a Text File with Cat or Touch
- Displaying a file
- (Con)cat
- Echoing
- Creating a File
- Using Touch to create a file instead
- Summary
- 4 Ways to Create a Text File in Linux Terminal
- Create file in Linux command line
- 1. Create an empty file using touch command
- 2. Create files using cat command
- 3. Create new file using echo command
- 4. Create a new file using a text editor like Nano or Vim
7 Ways to Create a File in Linux Terminal
In this tutorial, I will show you how to create a file from a Linux terminal. There are many text editors like (vim, nano, vi) and many commands like (cat, echo, printf, touch) to create a file in the Linux operating system via command line. Here will explain the following linux tools.
1) Create a file with touch command
We will use touch command with any extension to create file, this command will create an empty file touch.txt in your current directory as an example below.
To see the file type command below.
2) Create a file with cat command
We will use cat command to create file, this command will create an empty file cat.txt in your current directory as an example below, but you must add text in the file.
Add the text below.
To save the file hit Ctrl + d , and to see the file type command below.
To open the file, we will use cat command to open it.
3) Create a file with echo command
We will use echo command to create file, this command will create a file echo.txt in your current directory as an example below, but you should add text in the line command.
To see the file,type command below.
To open the file, we will use cat command to open it.
4) Create a file with printf command
We will use printf command to create file, this command will create a file printf.txt in your current directory as an example below, but you should add text in the line command.
To see the file type command below.
To open the file, we will use cat command to open it.
5) Create a file with nano text editor
To create a file using nano text editor, first install it, after that type command below and the text editor will be opened to adding text.
Add the text below.
To save the file type Ctrl + x and type y , to see the file type command below.
To open the file, We will use nano command to open it.
6) Create a file with vi text editor
To create a file using vi text editor, type command below and the text editor will open the file, but you can’t add any text before converting it to insert mode by typing i character.
Add the text below.
To save the file and exit hit Esc after that :wq , To see the file type command below.
To open the file, we will use vi command to open it.
7) Create a file with vim text editor
To create a file using vim text editor, type command below and the text editor will open the file, but you can’t add any text before converting it to insert mode by typing i character.
Add the text below.
To save the file and exit hit Esc after that :wq , to see the file type command below.
To open the file, we will use vim command to open it.
Conclusion
In this tutorial, we learned the different ways to create a file from Linux terminal. Hope you enjoyed reading and please leave your comments in the below comment section.
Источник
Команда cat Linux
Команда cat — это одна из самых часто используемых команд Linux. Она часто применяется опытными пользователями во время работы с терминалом. С помощью этой команды можно очень просто посмотреть содержимое небольшого файла, склеить несколько файлов и многое другое.
Несмотря на то что утилита очень проста и решает только одну задачу в лучшем стиле Unix, она будет очень полезной. А знать о ее дополнительных возможностях вам точно не помешает. В этой статье будет рассмотрена команда cat linux, ее синтаксис, опции и возможности.
Команда cat
Название команды — это сокращения от слова catenate. По сути, задача команды cat очень проста — она читает данные из файла или стандартного ввода и выводит их на экран. Это все, чем занимается утилита. Но с помощью ее опций и операторов перенаправления вывода можно сделать очень многое. Сначала рассмотрим синтаксис утилиты:
$ cat опции файл1 файл2 .
Вы можете передать утилите несколько файлов и тогда их содержимое будет выведено поочередно, без разделителей. Опции позволяют очень сильно видоизменить вывод и сделать именно то, что вам нужно. Рассмотрим основные опции:
- -b — нумеровать только непустые строки;
- -E — показывать символ $ в конце каждой строки;
- -n — нумеровать все строки;
- -s — удалять пустые повторяющиеся строки;
- -T — отображать табуляции в виде ^I;
- -h — отобразить справку;
- -v — версия утилиты.
Это было все описание linux cat, которое вам следует знать, далее рассмотрим примеры cat linux.
Использование cat в Linux
Самое простое и очевидное действие, где используется команда cat linux — это просмотр содержимого файла, например:
Команда просто выведет все, что есть в файле. Чтобы вывести несколько файлов достаточно просто передать их в параметрах:
Как вы знаете, в большинстве команд Linux стандартный поток ввода можно обозначить с помощью символа «-«. Поэтому мы можем комбинировать вывод текста из файла, а также стандартного ввода:
cat file — file1
Теперь перейдем к примерам с использованием ранее рассмотренных опций, чтобы нумеровать только непустые строки используйте:
Также вы можете нумеровать все строки в файле:
Опция -s позволяет удалить повторяющиеся пустые строки:
А с помощью -E можно сообщить утилите, что нужно отображать символ $ в конце каждой строки:
Если вы не передадите никакого файла в параметрах утилите, то она будет пытаться читать данные из стандартного ввода:
Для завершения записи нажмите Ctrl+D. Таким образом можно получить очень примитивный текстовый редактор — прочитаем ввод и перенаправим его вместо вывода на экран в файл:
cat > file2
$ cat file2
Возможность объединения нескольких файлов не была бы настолько полезна, если бы нельзя было записать все в один:
cat file1 file2 > file3
$ cat file3
Вот, собственно, и все возможности команды cat, которые могут быть полезны для вас.
Выводы
В этой статье мы рассмотрели что представляет из себя команда cat linux и как ею пользоваться. Надеюсь, эта информация была полезной для вас. Если у вас остались вопросы, спрашивайте в комментариях!
Источник
The Cat Command in Linux – How to Create a Text File with Cat or Touch
The cat command is a very popular and versatile command in the ‘nix ecosystem. There are 4 common usages of the cat command. It can display a file, concatenate (combine) multiple files, echo text, and it can be used to create a new file.
Displaying a file
The most common use of the cat command is to output the contents of a file. The following is an example that you can try.
In this simple example, we’re using a combination of echo and a redirect to create a file containing «Dance, Dance». We then use the cat command to display the contents.
The output is as follows:
The output of the example commands
(Con)cat
The previous example is actually a specific case of the cat command’s main function, which is to concatenate files for display. If we use the command the same way, but give it two or more files, then it outputs the concatenation for the files.
If we run the following commands:
The output is the contents of the 1st file, followed by the contents of the 2nd file. You can give cat many files and it will concatenate (combine) all of them. Notice however, that the cat command automatically inserts a line break between outputs.
The output of two files concatenated
cat also provides some switches to to do things such as show non-print characters (-v), or number your lines (-n). A complete breakdown can be found in the man pages.
Echoing
This is a less common usage of cat , but is the basis for the next section. If you run the cat command with no commands, cat will run in interactive mode and echo anything you type until you exit the command.
Running cat in interactive mode
In the example here, I’ve typed a single word per line. Each time I hit enter, the line was echoed.
You can also pipe text to cat , in which case that text is echoed. For example:
This will result in the following output:
Piping text into cat
Creating a File
In the previous examples, we’ve been using the echo command redirected to a file to create new files. Cat can be used in a similar way. In fact, we can use cat ‘s concat and echo functionality to create files.
We can create a file containing the concatenation of multiple files like this:
In the above example, we’re creating 3 files using echo , combining the 3 files into one using cat , and then displaying the new combined file using cat .
The result of the above commands. We’ve created 3 files, then combined them into a single file using cat
We can also use cat ‘s interactive mode to create a file with the text that we type into the terminal.
Each time you hit enter, it commits the text to the file. If you have uncommitted text and exit, it won’t be captured in the file.
This is a fantastic way to create a file quickly with the ability to enter the content of the file.
Using Touch to create a file instead
Sometimes you just need a file to exist. As an alternative to using cat to create a file, you can use the touch command.
The touch command was designed to update the modified timestamp of a file, but is commonly used as a quick way to create an empty file. Here is an example of that usage:
The touch command can create multiple files, update the modification and/or creation timestamps, and a bunch of other useful things. The full man pages can be found here.
Touch is commonly used to ensure that a file exists, and is a great command if you need an empty file quickly.
Summary
Cat is a very useful command. You can use it to create, display, and combine text files very quickly and easily.
If you only need a file to exist, but don’t mind (or require) it being empty, using touch is a great alternative.
Hughie Coles is a lead developer at Index Exchange. He writes about software architecture, scaling, leadership, and culture. For more of his writing, check out his blog on medium.
I’m Hughie, A software developer from Toronto. I’m currently a lead developer at Index Exchange. I write about scaling out, leadership, culture, and general dev stuff.
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States Federal Tax Identification Number: 82-0779546)
Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.
Donations to freeCodeCamp go toward our education initiatives and help pay for servers, services, and staff.
Источник
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.
Источник