Открыть файл через консоль linux

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.

Читайте также:  Astra linux смена пароля root

@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 😉

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

Читайте также:  Linux var from command

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.

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.

Читайте также:  How to get root access on linux

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

Источник

doctor Brain

Иногда, работая в терминале, возникает необходимость открыть какой-либо файл. Но при этом нет никакого желания возвращаться в менеджер файлов операционной системы (для MacOS — это Finder), искать путь к файлу и открывать или запускать его с помощью программы, предназначенной для взаимодействия с нужным нам файлом по умолчанию. Это долго и утомительно.

К счастью в терминале есть команда open , которая позволит нам открыть файл в UNIX-подобной операционной системе (в том числе в MacOS и Linux).

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

После команды через пробел указывается относительный или абсолютный путь к открываемому файлу.

Таким же образом можно открыть и сайт, указав его адрес:

А еще с помощью команды open можно открыть менеджер файлов операционной системы (для MacOS — это Finder) из текущей директории. В этом случае используется специальный символ . (точка):

Менеджер файлов можно открыть и для родительской директории. В таком случае нужно использовать две точки .. :

Чтобы сменить программу, в которой необходимо открыть файл, необходимо воспользоваться опцией -a :

Остальные опции и возможности команды open можно просмотреть из консоли с помощью команды:

Новые публикации

Photo by CHUTTERSNAP on Unsplash

JavaScript: сохраняем страницу в pdf

HTML: Полезные примеры

CSS: Ускоряем загрузку страницы

JavaScript: 5 странностей

JavaScript: конструктор сортировщиков

Категории

О нас

Frontend & Backend. Статьи, обзоры, заметки, код, уроки.

© 2021 dr.Brain .
мир глазами веб-разработчика

Источник

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