File end with in linux

Linux append text to end of file

You need to use the >> to append text to end of file. It is also useful to redirect and append/add line to end of file on Linux or Unix-like system.

How to redirect the output of the command or data to end of file

The procedure is as follows

  1. Append text to end of file using echo command:
    echo ‘text here’ >> filename
  2. Append command output to end of file:
    command-name >> filename

How to add lines to end of file in Linux

The >> is called as appending redirected output. Create the file if does not exists. For example, append some networking command to net.eth0.config.sh script:
echo ‘I=eth0’ >> net.eth0.config.sh
echo ‘ip link set $I up’ >> net.eth0.config.sh
echo ‘ip addr add 10.98.222.5/255.255.255.0 dev $I’ >> net.eth0.config.sh
echo ‘ip route add default via 10.98.222.1’ >> net.eth0.config.sh

You can also add data to other config files. Another option is to run command and append output to a file. Run data command at the terminal and append output to output.txt:
date >> output.txt
Execute ls command and append data to files.txt:
ls >> files.txt
To see files.txt use cat command:
cat files.txt
more files.txt
less files.txt

How to append standard output and standard error

The following sytax allows both the standard output (file descriptor 1) and the standard error output (file descriptor 2) to be appended to the file name. The format for appending standard output and standard error is:
echo ‘text’ &>>filename
command &>>filename
find . type d -name «*.projects» &>> list.txt
This is semantically equivalent to
echo ‘text’ >>fileNameHere 2>&1
command >>fileNameHere 2>&1
date >>data.txt 2>&1

For more info read redirection topic.

Append text when using sudo

Try the tee command:
echo ‘text’ | sudo tee -a my_file.txt
echo ‘104.20.186.5 www.cyberciti.biz’ | sudo tee -a /etc/hosts
Of coruse we can use following syntax to append text to end of file in Linux
sudo sh -c ‘echo my_text >> file1’
sudo — bash -c ‘echo «some data» >> /my/path/to/filename.txt’
The -c option passed to the bash/sh to run command using sudo.
See “how to append text to a file when using sudo command on Linux or Unix” for more info.

Conclusion – Append text to end of file on Unix

To append a new line to a text on Unix or Linux, try:

Источник

How to Append to End of a File in Linux

In this tutorial, we learn different ways to append text to the end of a file in Linux. You can achieve this using several methods in Linux, but the simplest one is to redirect the command output to the desired filename. Using the >> character you can output result of any command to a text file.

Other ways this can be achieved, is using Linux tools like tee, awk, and sed.

Redirect output of command or data to end of file

Every Unix-based operating system has a concept of “a default place for output to go”. Everyone calls it “standard output”, or “stdout”, pronounced standard out. Your shell (probably bash or zsh) is constantly watching that default output place. When your shell sees new output there, it prints it out on the screen so that you can see it.

We can redirect that output to a file using the >> operator.

The procedure is as follows:

Append text to end of file using echo command:

Append command output to end of file:

Adding lines to end of file

We can add text lines using this redirect character >> or we can write data and command output to a text file. Using this method the file will be created if it doesn’t exist.

Читайте также:  Ошибка cab файл windows

Adding command data output result to end of file

You can also add data or run command and append output to the desired file. In this example, we will use date for appending the current date to a file, uname command — which will print out kernel version of the Linux system we are using and lastly ls command which outputs the current directory structure and file list.
You can use any command that can output it’s result to a terminal, which means almost all of the command line tools in Linux.

Alternative methods

Let’s see how to append using tee, awk and sed Linux utility.

Using tee command line tool

Tee command reads the standard input and writes it to both the standard output and one or more files. The command is named after the T-splitter used in plumbing. It breaks the output of a program so that it can be both displayed and saved in a file.

Using awk command line tool

Awk is a utility that enables a programmer to write tiny but effective programs in the form of statements that define text patterns that are to be searched for in each line of a document and the action that is to be taken when a match is found within a line. Awk is mostly used for pattern scanning and processing.

Using sed command line tool

Sed command in Linux stands for stream editor and it can perform lots of functions on a file like searching, find and replace, insertion or deletion. By using sed you can edit files even without opening it, which is a much quicker way to find and replace something in the file.

Append multiple lines to a file

There are several ways to append multiple lines to a file at once.
You can, of course, add lines one by one:

Next variant is to enter new line in terminal:

Another way is to open a file and write lines until you type EOT:

Conclusion

Although there are multiple ways to append the text lines or data and command output to a file, we saw that the easiest way is using >> redirect character. There are ways to append the text to an end of a specific line number in a file, or in the middle of a line using regex, but we will going to cover that in some other article.

Let us know what method to append to the end of the file you think is best down in the comments section.

Источник

EOF — это не символ

Недавно я читал книгу «Компьютерные системы: архитектура и программирование. Взгляд программиста». Там, в главе про систему ввода-вывода Unix, авторы упомянули о том, что в конце файла нет особого символа EOF .

Если вы читали о системе ввода-вывода Unix/Linux, или экспериментировали с ней, если писали программы на C, которые читают данные из файлов, то это заявление вам, вероятно, покажется совершенно очевидным. Но давайте поближе присмотримся к следующим двум утверждениям, относящимся к тому, что я нашёл в книге:

  1. EOF — это не символ.
  2. В конце файлов нет некоего особого символа.

Что же такое EOF ?

EOF — это не символ

Почему кто-то говорит или думает, что EOF — это символ? Полагаю, это может быть так из-за того, что в некоторых программах, написанных на C, можно найти код, в котором используется явная проверка на EOF с использованием функций getchar() и getc() .

Это может выглядеть так:

Если заглянуть в справку по getchar() или getc() , можно узнать, что обе функции считывают следующий символ из потока ввода. Вероятно — именно это является причиной возникновения заблуждения о природе EOF . Но это — лишь мои предположения. Вернёмся к мысли о том, что EOF — это не символ.

А что такое, вообще, символ? Символ — это самый маленький компонент текста. «A», «a», «B», «b» — всё это — разные символы. У символа есть числовой код, который в стандарте Unicode называют кодовой точкой. Например — латинская буква «A» имеет, в десятичном представлении, код 65. Это можно быстро проверить, воспользовавшись командной строкой интерпретатора Python:

Или можно взглянуть на таблицу ASCII в Unix/Linux:

Выясним, какой код соответствует EOF , написав небольшую программу на C. В ANSI C константа EOF определена в stdio.h , она является частью стандартной библиотеки. Обычно в эту константу записано -1 . Можете сохранить следующий код в файле printeof.c , скомпилировать его и запустить:

Скомпилируем и запустим программу:

У меня эта программа, проверенная на Mac OS и на Ubuntu, сообщает о том, что EOF равняется -1 . Есть ли какой-нибудь символ с таким кодом? Тут, опять же, можно проверить коды символов в таблице ASCII, можно взглянуть на таблицу Unicode и узнать о том, в каком диапазоне могут находиться коды символов. Мы же поступим иначе: запустим интерпретатор Python и воспользуемся стандартной функцией chr() для того, чтобы она дала бы нам символ, соответствующий коду -1 :

Как и ожидалось, символа с кодом -1 не существует. Значит, в итоге, EOF , и правда, символом не является. Переходим теперь ко второму рассматриваемому утверждению.

Читайте также:  The nvidia opengl driver lost connection with the display driver due to exceeding the windows

В конце файлов нет некоего особого символа

Может, EOF — это особенный символ, который можно обнаружить в конце файла? Полагаю, сейчас вы уже знаете ответ. Но давайте тщательно проверим наше предположение.

Возьмём простой текстовый файл, helloworld.txt, и выведем его содержимое в шестнадцатеричном представлении. Для этого можно воспользоваться командой xxd :

Как видите, последний символ файла имеет код 0a . Из таблицы ASCII можно узнать о том, что этот код соответствует символу nl , то есть — символу новой строки. Это можно выяснить и воспользовавшись Python:

Так. EOF — это не символ, а в конце файлов нет некоего особого символа. Что же такое EOF ?

Что такое EOF?

EOF (end-of-file) — это состояние, которое может быть обнаружено приложением в ситуации, когда операция чтения файла доходит до его конца.

Взглянем на то, как можно обнаруживать состояние EOF в разных языках программирования при чтении текстового файла с использованием высокоуровневых средств ввода-вывода, предоставляемых этими языками. Для этого напишем очень простую версию cat , которая будет называться mcat . Она побайтно (посимвольно) читает ASCII-текст и в явном виде выполняет проверку на EOF . Программу напишем на следующих языках:

  • ANSI C
  • Python 3
  • Go
  • JavaScript (Node.js)

Вот репозиторий с кодом примеров. Приступим к их разбору.

ANSI C

Начнём с почтенного C. Представленная здесь программа является модифицированной версией cat из книги «Язык программирования C».

Вот некоторые пояснения, касающиеся вышеприведённого кода:

  • Программа открывает файл, переданный ей в виде аргумента командной строки.
  • В цикле while осуществляется копирование данных из файла в стандартный поток вывода. Данные копируются побайтово, происходит это до тех пор, пока не будет достигнут конец файла.
  • Когда программа доходит до EOF , она закрывает файл и завершает работу.

Python 3

В Python нет механизма явной проверки на EOF , похожего на тот, который имеется в ANSI C. Но если посимвольно читать файл, то можно выявить состояние EOF в том случае, если в переменной, хранящей очередной прочитанный символ, будет пусто:

Запустим программу и взглянём на возвращаемые ей результаты:

Вот более короткая версия этого же примера, написанная на Python 3.8+. Здесь используется оператор := (его называют «оператор walrus» или «моржовый оператор»):

Запустим этот код:

В Go можно явным образом проверить ошибку, возвращённую Read(), на предмет того, не указывает ли она на то, что мы добрались до конца файла:

JavaScript (Node.js)

В среде Node.js нет механизма для явной проверки на EOF . Но, когда при достижении конца файла делается попытка ещё что-то прочитать, вызывается событие потока end.

Низкоуровневые системные механизмы

Как высокоуровневые механизмы ввода-вывода, использованные в вышеприведённых примерах, определяют достижение конца файла? В Linux эти механизмы прямо или косвенно используют системный вызов read(), предоставляемый ядром. Функция (или макрос) getc() из C, например, использует системный вызов read() и возвращает EOF в том случае, если read() указывает на возникновение состояния достижения конца файла. В этом случае read() возвращает 0 . Если изобразить всё это в виде схемы, то получится следующее:

Получается, что функция getc() основана на read() .

Напишем версию cat , названную syscat , используя только системные вызовы Unix. Сделаем мы это не только из интереса, но и из-за того, что это вполне может принести нам какую-то пользу.

Вот эта программа, написанная на C:

В этом коде используется тот факт, что функция read() , указывая на достижение конца файла, возвращает 0 .

Вот та же программа, написанная на Python 3:

Вот — то же самое, написанное на Python 3.8+:

Запустим и этот код:

Итоги

  • EOF — это не символ.
  • В конце файлов нет некоего особого символа.
  • EOF — это состояние, о котором сообщает ядро, и которое может быть обнаружено приложением в том случае, когда операция чтения данных доходит до конца файла.
  • В ANSI C EOF — это, опять же, не символ. Это — константа, определённая в stdio.h , в которую обычно записано значение -1.
  • «Символ» EOF нельзя найти в таблице ASCII или в Unicode.

Уважаемые читатели! А вы знаете о каких-нибудь более или менее широко распространённых заблуждениях из мира компьютеров?

Источник

How to Find Files in Linux Using the Command Line

When you have to find a file in Linux, it’s sometimes not as easy as finding a file in another operating system. This is especially true if you are running Linux without a graphical user interface and need to rely on the command line. This article covers the basics of how to find a file in Linux using the CLI. The find command in Linux is used to find a file (or files) by recursively filtering objects in the file system based on a simple conditional mechanism. You can use the find command to search for a file or directory on your file system. By using the -exec flag ( find -exec ), files can be found and immediately processed within the same command.

Find a File in Linux by Name or Extension

Use find from the command line to locate a specific file by name or extension. The following example searches for *.err files in the /home/username/ directory and all sub-directories:

Using Common find Commands and Syntax to Find a File in Linux

find expressions take the following form:

  • The options attribute will control the find process’s behavior and optimization method.
  • The starting/path attribute will define the top-level directory where find begins filtering.
  • The expression attribute controls the tests that search the directory hierarchy to produce output.
Читайте также:  Windows сам закрывает папки

Consider the following example command:

This command enables the maximum optimization level (-O3) and allows find to follow symbolic links ( -L ). find searches the entire directory tree beneath /var/www/ for files that end with .html .

Basic Examples

Command Description
find . -name testfile.txt Find a file called testfile.txt in current and sub-directories.
find /home -name *.jpg Find all .jpg files in the /home and sub-directories.
find . -type f -empty Find an empty file within the current directory.
find /home -user exampleuser -mtime -7 -iname «.db» Find all .db files (ignoring text case) modified in the last 7 days by a user named exampleuser.

Options and Optimization for find

The default configuration for find will ignore symbolic links (shortcut files). If you want find to follow and return symbolic links, you can add the -L option to the command, as shown in the example above.

find optimizes its filtering strategy to increase performance. Three user-selectable optimization levels are specified as -O1 , -O2 , and -O3 . The -O1 optimization is the default and forces find to filter based on filename before running all other tests.

Optimization at the -O2 level prioritizes file name filters, as in -O1 , and then runs all file-type filtering before proceeding with other more resource-intensive conditions. Level -O3 optimization allows find to perform the most severe optimization and reorders all tests based on their relative expense and the likelihood of their success.

Command Description
-O1 (Default) filter based on file name first.
-O2 File name first, then file type.
-O3 Allow find to automatically re-order the search based on efficient use of resources and likelihood of success.
-maxdepth X Search current directory as well as all sub-directories X levels deep.
-iname Search without regard for text case.
-not Return only results that do not match the test case.
-type f Search for files.
-type d Search for directories.

Find a File in Linux by Modification Time

The find command contains the ability to filter a directory hierarchy based on when the file was last modified:

The first command returns a list of all files in the entire file system that end with the characters conf and modified in the last seven days. The second command filters exampleuser user’s home directory for files with names that end with the characters conf and modified in the previous three days.

Use grep to Find a File in Linux Based on Content

The find command can only filter the directory hierarchy based on a file’s name and metadata. If you need to search based on the file’s content, use a tool like grep . Consider the following example:

This searches every object in the current directory hierarchy ( . ) that is a file ( -type f ) and then runs the command grep «example» for every file that satisfies the conditions. The files that match are printed on the screen ( -print ). The curly braces ( <> ) are a placeholder for the find match results. The <> are enclosed in single quotes ( ‘ ) to avoid handing grep a malformed file name. The -exec command is terminated with a semicolon ( ; ), which should be escaped ( \; ) to avoid interpretation by the shell.

How to Find and Process a File in Linux

The -exec option runs commands against every object that matches the find expression. Consider the following example:

This filters every object in the current hierarchy ( . ) for files named rc.conf and runs the chmod o+r command to modify the find results’ file permissions.

The commands run with the -exec are executed in the find process’s root directory. Use -execdir to perform the specified command in the directory where the match resides. This may alleviate security concerns and produce a more desirable performance for some operations.

The -exec or -execdir options run without further prompts. If you prefer to be prompted before action is taken, replace -exec with -ok or -execdir with -okdir .

How to Find and Delete a File in Linux

To delete the files that end up matching your search, you can add -delete at the end of the expression. Do this only when you are positive the results will only match the files you wish to delete.

In the following example, find locates all files in the hierarchy starting at the current directory and fully recursing into the directory tree. In this example, find will delete all files that end with the characters .err :

More Information

You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

This page was originally published on Monday, October 25, 2010.

Источник

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