Открываем txt в линукс

How do I open a text file in my terminal?

Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.

There is a file named RESULTS.txt and I want to open this file in my terminal. (I mean I want to see the file contents be displayed in the terminal and not in some text editor) How do I do that ?

@Sparksis When I search for «open a text file in a terminal» I get results from mac forums for things like pico, etc. which aren’t in ubuntu. This kind of question is very much welcome here.

You might want to look into some beginner Ubuntu shell tutorials — They will explain how to do this and related stuff.

16 Answers 16

directly shows a text file in the terminal.

lets you scroll and search ( / text to search Enter ) in the file; press q to exit.

cat /home/john/RESULTS.txt less /home/john/RESULTS.txt 

upon entering a command like cat /home/suhail/RESULT.txt I get this cat: /home/suhail/RESULT.txt: No such file or directory

If you’re in the same folder as the file, you don’t need to do the full path. You can just do cat RESULT.txt

@SuhailGupta: There might be more than one suhail directory. /home/suhail is normally your home directory. What does pwd print? Also, tab completion can be very convenient; if you type cat R , and there’s only one file in the current directory whose name starts with R , it will expand to the name of that file.

Another alternative is vim .

Once you opened a file with vim you can insert text by typing i , for instance. If you want to save your file use :w (write) or :q (quit) or :wq (for write and quit) or :q! (quit and do not save). Sometimes you need to hit the ESC key to be able to type the commands.

Vim requires some learning, but is widely used and it is very versatile.

Vim is an advanced text editor that provides the power of the de-facto Unix editor ‘Vi’ with a more complete feature set. Vim is often called a «programmer’s editor,» and is so useful for programming that many consider it an entire IDE. It’s not just for programmers, though. Vim is perfect for all kinds of text editing, from composing email to editing configuration files.

An even better alternative is view , which starts Vim in read-only mode on Ubuntu. And since the OP asked to view and explicitly not to edit . -1 . of course I will take back the downvote in case this gets edited.

@0xC0000022L 🙂 You can keep the downvote. Feel free to add an answer on view if you want to. Vim is perfectly capable of showing files and thus this answers the question.

I upvoted your comment first. Fine with me. But since you mentioned Vim, view would literally fit into your answer instead of a separate one. I still think that and not in some text editor is pretty clear 😉

Читайте также:  Linux system disk space

view is a dumb four letter alias for vim -R . If you don’t use any save command like ZZ , :w or 😡 , there is no difference. Also you can redirect files to vim to use it as a reader: command | vim — . This is usually better than less , the only downside being that vim snarfs the entire output before displaying anything.

@0xC0000022L: for someone fairly new to using the command line, “in the terminal and not in some text editor” could easily mean “in some utility within the terminal, not in some text editor that opens in a separate window”. When I first came to the command line, I was so used to identifying applications with their windows that I certainly thought of vim , nano , etc. as part of the terminal rather than as separate applications for quite a while.

all those are best ways and there is one more way to do this & that’s with head command.

both will give you the same input.

Head command Explanation:

Generally head command used to print the starting lines of the any text file.we can view the text file with

That will prints the 1st 10 lines of the above text file.

If you want to specific on the number of lines which are to be view then you can use head as

Then in the above text file first 20 lines will be viewed.

If you want to view whole file data with head means then then we can get it by

Hope that above explanation will give you some idea on usage of head.

This is just a really bad way to write cat . If that’s what this is meant to be, then there’s far more than this one more way to do it…

If the file is rather long, you might want to use

so that you can navigate through it with directional keys.

to print out the last 30 lines of a large file named result.txt .

It will show you the last ten lines of your_file . If a process appends something to this file, you see it on your terminal. man tail gives you more on tail .

It’s useful to see what happens with a server when you use this command on a log file.

Press Ctrl — C to quit when you are done viewing.

There are a lot of alternatives for doing that:

Some of these programs have a lot of parameters, so check that out with —help after the command..

  • cat filename prints the whole file at once
  • more / less filename similar behaviour for see the file in parts
  • tail filename start reading from the tail of the file
  • grep text filename for filtering results

Hope that some of this works for you..

With a terminal text editor: nano /path/to/file/RESULTS.txt

As we seem to be listing all available alternatives of displaying any text file in the terminal, it would be quite fun to introduce pv as technically one valid (but unusual) method, although I would normally use cat instead for most things.

Читайте также:  Phpmyadmin установка kali linux

It is in the repositories and so can be installed with sudo apt-get install pv if you don’t have it already.

As the man page notes, pv is very often used to

monitor the progress of data through a pipe. pv will copy each supplied FILE in turn to standard output (- means standard input), or if no FILEs are specified just standard input is copied. This is the same behaviour as cat(1).

With pv you can literally print the file to the screen, and choose the rate ( -L ) at which it appears. The example below uses a high rate (300), but if you choose a low rate such as -L 50 , it will appear as if the computer is typing out the file for you.

pv /etc/apt/sources.list -qL 300 

Needless to say you can increase the rate further ( -L 8000 ), and the command becomes very similar to cat , with the output appearing instantaneously.

For more information see man pv or the Ubuntu manpages online.

Источник

Sysadminium

На этом уроке по Linux мы рассмотрим создание (touch), редактирование (nano) и чтение (cat, tac, grep, less, tail) текстовых файлов.

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

Все примеры я буду показывать на Debian 11, так как на Ubuntu 22.04 все выполняется аналогично. Вообще в Linux работа в терминале на любых системах практически одинакова. Поэтому создание, редактирование и чтение файлов можно продемонстрировать на любой системе.

Для создания текстового файла служит команда touch:

С помощью команды ls можно посмотреть какие файлы есть в каталоге:

Для команды ls есть дополнительные опции:

  • -l — показывает информацию по каждому файлу;
  • -h — показывает размер файла в удобном для человека виде (байты, килобайты, мегабайты и т.д.). Эту опцию можно использовать только вместе в -l.

Опции можно писать слитно (ls -lh) или раздельно (ls -l -h). Вот пример:

alex@deb:~$ ls -lh итого 0 -rw-r--r-- 1 alex alex 0 ноя 26 16:15 file.txt

Команда touch не только создает файл, но если этот файл уже есть, то обновляет время доступа и модификации данного файла:

alex@deb:~$ touch file.txt alex@deb:~$ ls -lh итого 0 -rw-r--r-- 1 alex alex 0 ноя 26 16:17 file.txt

Как вы могли заметить вначале время последнего изменения файла было 16:15, а после выполнения команды touch оно изменилось на 16:17. На самом деле команда touch не изменила файл, она лишь прикоснулась к файлу и тем самым изменила его время доступа. Кстати, с английского touch переводится как прикасаться.

Давайте теперь разберём вывод команды ls -lh:

Тип файла | Права | | Кол-во ссылок | | | Владелец | | | | Группа | | | | | Размер | | | | | | Дата и время последнего касания или изменения | | | | | | | Имя файла | | | | | | | | - rw-r--r-- 1 alex alex 0 ноя 26 16:17 file.txt

Пока что вам нужно запомнить что таким образом можно посмотреть размер файла и дату его изменения, с остальным разберемся позже. И ещё запомните 2 типа файлов:

  • знак тире «-« — это обычный файл;
  • символ «d» — это каталог;
  • есть и другие типы файлов, но пока их рассматривать не будем.

Редактирование файлов

Отредактировать текстовый файл можно с помощью текстового редактора «nano»:

После выполнения этой команды у Вас откроется текстовый редактор:

Читайте также:  Сброс всех настроек линукс

Для того чтобы сохранить этот файл нужно нажать комбинацию клавиш «Ctrl+o«.

А чтобы закончить редактирование и закрыть этот файл нужно нажать «Ctrl+x«. При этом у вас спросят, хотите ли вы сохранить этот файл и если да, то нужно ввести «y» и нажать клавишу «Enter«. Таким образом необязательно использовать комбинацию «Ctrl+o» перед закрытием файла.

Внизу я выделил подсказки текстового редактора Nano, в подсказках символ «^» — это клавиша Ctrl.

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

Чтение файлов

Команды cat и tac

Давайте теперь научимся читать текстовые файлы. Чаще всего для этого используется команда cat:

alex@deb:~$ cat file.txt И тут мы можем вводить текст, какой только пожелаем.

У команды cat есть опция -n, которая выводит номера строк:

alex@deb:~$ cat -n file.txt 1 И тут мы можем 2 вводить текст, 3 какой только пожелаем.

Для команды cat есть команда перевёртыш, это команда tac. Она выводит текст задом наперед:

alex@deb:~$ tac file.txt какой только пожелаем. вводить текст, И тут мы можем

Команда grep

Если Вам нужно что-то найти в тексте, то для этого используйте команду grep. Например, мы ищем строку в которой встречается слово «какой»:

alex@deb:~$ grep какой file.txt какой только пожелаем.

Команда less

Если текст длинный то вместо cat лучше использовать команду less:

alex@deb:~$ less /etc/ssh/sshd_config

Используя less мы можем кнопками вверх / вниз перемещаться по тексту:

Если нажать кнопу «/», то откроется строка, куда можно ввести фразу для поиска в этом файле. Давайте, например, найдём строку со словом «Port»:

При поиске удобно использовать кнопку «n» для дальнейшего поиска введенной фразы, и комбинацию «Shift+n» для поиска в обратном направлении (к началу файла). Для выхода из программы используйте клавишу»q«.

Команды tail и head

Если Вам нужно посмотреть последние строки файла используйте команду «tail«:

alex@deb:~$ tail /etc/ssh/sshd_config # override default of no subsystems Subsystem sftp /usr/lib/openssh/sftp-server # Example of overriding settings on a per-user basis #Match User anoncvs # X11Forwarding no # AllowTcpForwarding no # PermitTTY no # ForceCommand cvs server

А если нужно посмотреть первые строки файла то команду «head«:

alex@deb:~$ head /etc/ssh/sshd_config # $OpenBSD: sshd_config,v 1.103 2018/04/09 20:41:22 tj Exp $ # This is the sshd server system-wide configuration file. See # sshd_config(5) for more information. # This sshd was compiled with PATH=/usr/bin:/bin:/usr/sbin:/sbin # The strategy used for options in the default sshd_config shipped with # OpenSSH is to specify options with their default value where # possible, but leave them commented. Uncommented options override the

Эти две команды выводят 10 последних (tail) или 10 первых (head) строк файла. И у этих команд есть параметр -n, с помощью которого можно указать сколько строк выводить, например выведем по 3 строки:

alex@deb:~$ tail -n 3 /etc/ssh/sshd_config # AllowTcpForwarding no # PermitTTY no # ForceCommand cvs server alex@deb:~$ head -n 3 /etc/ssh/sshd_config # $OpenBSD: sshd_config,v 1.103 2018/04/09 20:41:22 tj Exp $ # This is the sshd server system-wide configuration file. See

А ещё команда tail позволяет выводить изменяющиеся файлы, например логи. Для этого используется опция -f. Чтобы закончить наблюдение за файлом, нужно нажать комбинацию Ctrl+c.

Источник

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