Как создать txt линукс

Create text file and fill it using bash

I need to create a text file (unless it already exists) and write a new line to the file all using bash. I’m sure it’s simple, but could anyone explain this to me?

9 Answers 9

Creating a text file in unix can be done through a text editor (vim, emacs, gedit, etc). But what you want might be something like this

echo "insert text here" > myfile.txt 

That will put the text ‘insert text here’ into a file myfile.txt. To verify that this worked use the command ‘cat’.

If you want to append to a file use this

echo "append this text" >> myfile.txt 

If you’re wanting this as a script, the following Bash script should do what you want (plus tell you when the file already exists):

#!/bin/bash if [ -e $1 ]; then echo "File $1 already exists!" else echo >> $1 fi 

If you don’t want the «already exists» message, you can use:

#!/bin/bash if [ ! -e $1 ]; then echo >> $1 fi 

Save whichever version with a name you like, let’s say «create_file» (quotes mine, you don’t want them in the file name). Then, to make the file executatble, at a command prompt do:

create_file NAME_OF_NEW_FILE 

The $1 is a special shell variable which takes the first argument on the command line after the program name; i.e. $1 will pick up NAME_OF_NEW_FILE in the above usage example.

@Switz: See edit explaining $1. If you replace $1 in the script with «text.txt», it will always use «text.txt» as the filename.

Assuming you mean UNIX shell commands, just run

echo prints a newline, and the >> tells the shell to append that newline to the file, creating if it doesn’t already exist.

In order to properly answer the question, though, I’d need to know what you would want to happen if the file already does exist. If you wanted to replace its current contents with the newline, for example, you would use

EDIT: and in response to Justin’s comment, if you want to add the newline only if the file didn’t already exist, you can do

test -e file.txt || echo > file.txt 

At least that works in Bash, I’m not sure if it also does in other shells.

Источник

Как создать и отредактировать текстовый файл с помощью терминала в Linux

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

Команда контент-менеджеров wikiHow тщательно следит за работой редакторов, чтобы гарантировать соответствие каждой статьи нашим высоким стандартам качества.

Количество просмотров этой статьи: 45 592.

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

Читайте также:  Astra linux postgresql перезапуск

Как открыть терминал

Изображение с названием Create and Edit Text File in Linux by Using Terminal Step 1

Изображение с названием Create and Edit Text File in Linux by Using Terminal Step 2

В терминале введите ls и нажмите ↵ Enter . Терминал откроется в домашнем каталоге, но с помощью команды ls можно открыть список папок текущего каталога. Чтобы создать текстовый файл в одной из этих папок, необходимо перейти в нее из текущего каталога.

Изображение с названием Create and Edit Text File in Linux by Using Terminal Step 3

Выберите папку, в которой будет создан текстовый файл. Имя папки введите после команды ls , чтобы перейти в эту папку.

Изображение с названием Create and Edit Text File in Linux by Using Terminal Step 4

  • Например, введите cd Desktop , чтобы перейти в каталог рабочего стола.
  • Чтобы создать текстовый файл в одной из подпапок выбранной папки, после имени папки введите символ «/» (без кавычек), а затем введите имя подпапки. Например, если в папке «Documents» есть нужная вам подпапка «Misc», введите cd Documents/Misc .

Изображение с названием Create and Edit Text File in Linux by Using Terminal Step 5

Нажмите ↵ Enter . Команда будет выполнена, то есть вы перейдете из текущего каталога в выбранную папку (или подпапку).

Изображение с названием Create and Edit Text File in Linux by Using Terminal Step 6

Выберите текстовый редактор. Можно быстро создать простой текстовый файл; также можно воспользоваться текстовым редактором Vim или Emacs, чтобы создать и отредактировать более сложный текстовый файл. Теперь, когда вы перешли в нужную папку, создайте текстовый файл.

Источник

Как быстро создать пустой и непустой текстовый файл в Linux через терминал?

Ответ общий, вы можете исправить его, если считаете нужным.

Существует N-ое количество способов создания текстовых файлов, мы приведём два основных, которые, на наш взляд, самые быстрые с точки зрения клавиатурного ввода, и несколько других.

Под фразой «при вводе» подразумевается, что нужно ввести команду в терминал и нажать клавишу Enter .

Создание пустых файлов

При вводе этой команды в текущей директории будет создан пустой файл с именем a .

Можно вводить без пробела:

Более читаемый вариант, помогает не ошибиться и не записать случайно результат предыдущей команды в файл:

Можно создать сразу сколь угодно файлов:

Хотя так удобней (о touch будет далее):

Создание файлов с текстом

При вводе этой команды в текущей директории будет создан файл с именем h , содержащий текст blablabla и один перевод строки.

Можно вводить без пробела вокруг оператора > :

Выводимый контекст можно заключить в кавычки, а можно и не заключать, даже если он содержит пробелы:

echo bla bla bla > j echo 'bla bla bla' > k echo "bla bla bla" > l 

Все три вышеперечисленные команды дают одинаковый результат (кроме имён файлов, естественно).

Также можно провернуть такую штуку:

При вводе этой команды в текущей директории будут созданы два пустых файла: m и n ; и файл o , содержащий текст 123 и один перевод строки.

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

Ман по man ‘у . При вводе этой команды в текущей директории будет создан файл с именем p , содержащий мануал по команде man .

Другие способы создания файлов

Создание пустого файла с помощью touch

При вводе этой команды в текущей директории будет создан пустой файл с именем q .

Если быть точным, то touch это команда, основное назначение которой изменить время последнего изменения или последнего доступа файла, если же файл не существует, то она создает его. Цитата.

Создание файла «с текстом» с помощью cat

При вводе этой команды в текущей директории будет создан пустой файл с именем r и терминал перейдёт в режим конкатенации вводимых строк к концу содержимого этого файла. То есть мы можем сразу же начать заполнять файл текстом. Сохранение набранного текста будет происходит построчно по нажатию клавиши Enter . Иными словами, по нажатию клавиши Enter будет выполняться конкатенация.

Можно вводить без пробела:

Пример

  • Вводим cat>s — в текущей директории создан пустой файл с именем s .
  • Набираем 123 — этого текста ещё не будет в файле.
  • Нажимаем Enter — текст 123 записался в файл и курсор, как в терминале, так и в файле, перешёл на новую строку.
Читайте также:  Atheros ar9271 kali linux

На строку выше вернуться нельзя.

Выйти из режима конкатенации можно с помощью Ctrl+D (EOF — End Of File) в начале строки. Если вы уже начали набирать строку, Ctrl+D не закончит ввод файла, но запишет набранную часть строки без символа конца строки. Так вы можете записывать строки частями. Для выхода с незавершённой строкой можно нажать Ctrl+D дважды, тогда последняя строка в файле не будет иметь символа конца строки (EOL — End Of Line).

Создание файла с помощью редактора.

Очевидно, что мы можем исользовать редактор типа nano , vi , vim , etc для создания файла.

  1. Вводим nano t — открывается редактор nano в терминальном режиме.
  2. Вводим 123 и нажимаем Ctrl + O (не ноль, а буква), а затем Enter — в текущей директории создался файл с именем t , содержащий текст 123 и один перевод строки.
  3. Чтобы выйти и редактора нажимаем Ctrl + X (внизу редактора подсказки).

Создание файла с данными через dd

Полезно иногда создавать файл определенного размера с нулями

dd if=/dev/zero of=./file bs=10M count=100 
dd if=/dev/urandom of=./file bs=10M count=100 

Создается файл из 100 блоков по 10 мегабайт — 1 ГБ.

Выделение места под файл средствами файловой системы

Такие команды работают быстерее dd потому как сами данные не записываются, а просто выделяется область диска

fallocate резервирует место под файл на диске, а truncate обрезает файл или добавляет до нужного размера, резервируя место на диске.

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

Источник

How to create a simple .txt (text) file using terminal? [closed]

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

I’m just trying to review basic terminal commands. Having said that, how do I create a text file using the terminal only?

Although the question is really too broad, a quick tutorial (vim, editors, shell command redirection and so on) could be useful for the future, particularly together with the view count and the voting scores of the post and the answers. Maybe it would be most useful as a community wiki post.

5 Answers 5

You can’t use a terminal to create a file. You can use an application running in a terminal. Just invoke any non-GUI editor ( emacs -nw , joe , nano , vi , vim , …).

If you meant using the command line, then you are asking how to create a file using the shell. See What is the exact difference between a ‘terminal’, a ‘shell’, a ‘tty’ and a ‘console’?

The basic way to create a file with the shell is with output redirection. For example, the following command creates a file called foo.txt containing the line Hello, world.

If you want to write multiple lines, here are a few possibilities. You can use printf .

printf '%s\n' 'First line.' 'Second line.' 'Third line.' >foo.txt 

You can use a string literal containing newlines.

echo 'First line. Second line. Third line.' >foo.txt 
echo $'First line.\nSecond line.\nThird line.' >foo.txt 

Another possibility is to group commands.

On the command line, you can do this more directly with cat . Redirect its output to the file and type the input line by line on cat ‘s standard input. Press Ctrl + D at the beginning of the line to indicate the end of the input.

$ cat >foo.txt First line. Second line. Third line. Ctrl+D 

In a script you would use a here document to achieve the same effect:

cat foo.txt First line. Second line. Third line. EOF 

If you just want to create an empty file, you can use the touch command: it creates the file if it doesn’t exist, and just updates its last-modified date if it exists.

Читайте также:  Linux не боится вирусов

i.e. open foo.txt for appending, but write 0 bytes to it — this creates the file but doesn’t modify it. Unlike touch , this doesn’t update the file’s last-modified date if it already existed.

To create an empty file, and remove the file’s content if the file already existed, you can use

Thanks. I know about redirection, but have hard time finding documentation for the line >foo.txt , where there is nothing to redirect (no command before > ).

@Alexey It’s an empty command. An empty command does nothing, but its redirections are performed, which can have visible effects: an error if the file can’t be opened, creating the file if it didn’t exist for > and >> , truncating the file if it exists for < , processing the here-document for

I thought the empty command had to be evoked explicitly as : . I would like to understand the rules that allow $ >foo.txt , but disallow $ |cat .

touch ~/Desktop/something.txt 

This will create an empty txt file.

echo "Hello" > ~/Desktop/somethingelse.txt 

This will create a txt file saying «Hello».

nano ~/Desktop/anotherfile.txt 

This will open ~/Desktop/anotherfile.txt in nano , or if it doesn’t exist, it will create it and open it in nano .

The same can be done by simply replacing nano with emacs or vim and it will use emacs or vim instead of nano

All it takes to create an empty file is:

Something helpful when you’re stuck and must create a multiline textfile on the command line is something like this:

# cat textfile > This "should" > prove useful, 'maybe'. > EOF # cat textfile This "should" prove useful, 'maybe'. 

You can substitute cat for another command, for instance grep and a pattern, and have grep do its job on your input and this would output to file in the same fashion.

You can use either nano, vi or emacs editing program to create file on terminal level. If you’re using x windows system you’ll need to tell your system not to use the program in the GUI; but anyways, I’ll use emacs as an example.

 emacs filename.txt (press enter) - it will create an empty file with the filename specified "filename.txt". It will save "filename.txt" from which ever directory type in "emacs filename.txt" command. 

keep in mind in all UNIX system VI comes with it; emacs doesn’t, you’ll need to install emacs. Nano on the other hand is more popular; just in case if that doesn’t respond it means when you «nano filename.ext» and nothing happens you’ll need to install it.

once you issue vi filename.txt most likely you’ll end up creating a new file. You should look up vi, emacs or nano how to use on google before you get started. How to write a file, editing it, using its tools to search and replace text is different in those editing programs. I like emacs out of all the choices but you’ll find developers that are obsessed with or favor vi and nano

Источник

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