Linux command line print file

lpr: печать из командной строки

Команда lpr (line printer) печатает файл из терминала Linux. Утилита lpr помещает один или несколько файлов в очередь печати. Концепция очереди позволяет нескольким пользователям системы направлять вывод на один принтер. Очередь печатается последовательно, то есть первый файл в очереди будет напечатан первым. Если вы редактируете большинство своих файлов в консольных редакторах, таких как vim или nano, и хотите быстро распечатать набранный текст, вы найдете команду lpr очень легкой в употреблении и удобной. Для того, чтобы печатать с помощью команды lpr, необходимо установить пакет System printer configuration. Это можно сделать с помощью следующих команд:

В Debian/Ubuntu:

В Fedora/Cent OS/RedHat:

В других дистрибутивах пакет system-config-printer также должен иметься в репозиториях.

Откройте его и кликните Add.

Выберите и добавьте свой принтер

Команда lpr:

Для печати тестового файла просто введите:

Список сетевых принтеров:

Чтобы получить список всех доступных сетевых принтеров, введите команду:

Печать на заданный принтер:

Если доступно несколько принтеров, вы можете использовать опцию -P, чтобы указать нужный вам принтер.

Пробел после -P вставлять необязательно:

Проверка состояния:

Проверить состояние очереди печати определенного принтера можно с помощью команды lpq.

Очистка очереди печати:

Как вы могли видеть из вывода приведенной выше команды, каждая очередь печати имеет уникальный id. Вы можете удалить файлы из очереди печати с помощью команды lprm:

Чтобы отменить все задания на печать, используется следующая команда:

Печать всех файлов в директории:

Это очень простой трюк, чтобы напечатать все файлы с одинаковым расширением в директории. Вы должны перейти в эту директорию Введите следующую команду, чтобы распечатать все текстовые файлы в директории:

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

Источник

Печать из командной строки Linux

Оригинал: Printing from the Linux command line
Автор: Sandra Henry-Stocker
Дата публикации: 20 марта 2019 года
Перевод: А. Кривошей
Дата перевода: апрель 2016 г.

Печать из командной строки Linux очень проста. Вы используете команду lp, чтобы запросить печать, и lpq, чтобы увидеть, какие задания на печать находятся в очереди, но все становится немного сложнее, когда вы хотите печатать на двух сторонах листа или в портретном режиме. И есть много других вещей, которые вы можете захотеть сделать — например, распечатать несколько копий документа или отменить задание на печать. Давайте проверим некоторые опции, чтобы, когда вы печатаете из командной строки, ваши распечатки выглядели именно так, как вы хотите.

Вывод параметров принтера

Чтобы просмотреть настройки принтера из командной строки, используйте команду lpoptions. Вывод должен выглядеть примерно так:

Этот вывод, вероятно, будет немного более дружественным к человеку, если вы превратите его пробелы в возврат каретки. Обратите внимание, сколько настроек указано в списке.

ПРИМЕЧАНИЕ. В приведенном ниже выводе некоторые строки были повторно связаны, чтобы сделать этот вывод более читабельным.

С опцией -v команда lpinfo выведет список драйверов и связанной с ними информации.

Команда lpoptions покажет настройки вашего принтера по умолчанию. Используйте параметр -p, чтобы указать один из нескольких доступных принтеров.

Команда lpstat -p отображает состояние принтера, а команда lpstat -p -d также выводит список доступных принтеров.

Полезные команды

Чтобы распечатать документ на принтере по умолчанию, просто используйте команду lp, а затем имя файла, который вы хотите распечатать. Если имя файла содержит пробелы (что редко встречается в системах Linux), либо поместите имя в кавычки, либо начните вводить имя файла и нажмите клавишу табуляции, чтобы вызвать завершение файла (как показано во втором примере ниже).

Читайте также:  Windows server remote management console

Команда lpq отображает очередь печати.

Команда lp с опцией -n позволяет вам указать количество копий, которое вы хотите напечатать.

Чтобы отменить задание на печать, вы можете использовать команду cancel или lprm. Если вы не будете действовать быстро, то можете увидеть это:

Двусторонняя печать

Чтобы печатать в двухстороннем режиме, вы можете ввести команду lp с параметром sides, в котором указано, как печатать на обеих сторонах листа, и вид переплета (сбоку или сверху). Этот параметр представляет обычный способ, при которым вы получите двусторонний документ в портретном режиме.

Если вы хотите, чтобы все ваши документы печатались в двухстороннем режиме, вы можете изменить настройки lp для sides с помощью команды lpoptions.

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

Печать в ландшафтном режиме

Для печати в ландшафтном режиме вы должны использовать параметр landscape с командой lp.

Система печати, используемая в системах Linux, — это основанная на стандартах система печати с открытым исходным кодом, называемая CUPS, первоначально обозначавшая Common Unix Printing System. Она позволяет компьютеру выступать в качестве сервера печати.

Источник

How to Print files in Linux Using Command Line

Printing a file is one of the basic functionalities provide by the linux operating system, rather than just printing a file its provides us with a variety of options like to reformat it to adjust the margins, highlight some words, change text orientation and more. Undoubtedly we can print a file directly without passing any extra parameters but that would lead to a less appealing print, so here we see how to print a file and add optional parameters to make it look even better.

How to Print using pr command?

pr command is used as a basic command to print files, it has following syntax –

pr command does minor formatting to the input file you want to print by supplying options into the pr command, also pr command displays the file to user before printing it.

Here are the other options you can provide along with the pr command –

pr command options Usage
-k gives output in k columns
-t removes header and top/bottom margins from print
-d adds double spaces between the outputs
-h takes item to next header

Printing file where k=2, to print the output in 2 columns –

How to Print using lp/lpr command?

Unlike pr command, lp/lpr can be directly used to print out onto the printer without displaying the file on user’s terminal. Once you are ready with formatting using the pr command, you can use any of these commands to print your file on the printer connected to your computer.

To use lp command make sure you set the default printer, the lp command shows an ID that you can use to cancel the print job or check its status.

  • If you are using the lp command, you can use the -nNum option to print Num numberof copies. Along with the command lpr, you can use -Num for the same.
  • If there are multiple printers connected with the shared network, then you can choose a printer using -dprinter option along with lp command and for the same purpose you can use -Pprinter option along with lpr command. Here printer is the printer name.

Check and Abort file printing using lpstat and cancel command

lpstat command can be used to get a view of the printer’s queue, they may include – request IDs, owners, file sizes, when the jobs were sent for printing, and the status of the requests. We can use lpstat -o to see all output requests

The cancel command terminates a printing request from the lp command. The lprm command terminates all lpr requests. You can specify either the ID of the request (displayed by lp or lpq) or the name of the printer, to cancel whatever request is currently printing, regardless of its ID, simply enter cancel and the printer name –

Along with following commands there are even more commands like lpq (similar to lpstat) , lprm (command will cancel the active printing job if it belongs to you), etc.

Источник

How can I display the contents of a text file on the command line?

I would like to display the contents of a text file on the command line. The file only contains 5-6 characters. Is there an easy way to do this?

8 Answers 8

Using cat

Since your file is short, you can use cat .

Using less

If you have to view the contents of a longer file, you can use a pager such as less .

You can make less behave like cat when invoked on small files and behave normally otherwise by passing it the -F and -X flags.

I have an alias for less -FX . You can make one yourself like so:

If you add the alias to your shell configuration, you can use it forever.

Using od

If your file contains strange or unprintable characters, you can use od to examine the characters. For example,

Even though everybody uses cat filename to print a files text to the standard output first purpose is concatenating. From cat’s man page:

cat — concatenate files and print on the standard output

Now cat is fine for printing files but there are alternatives:

The ( ) return the value of an expression, in this case the content of filename which then is expanded by $ for echo or printf .

This does exactly what you want and is easy to remember.

Here is an example that lets you select a file in a menu and then prints it.

Источник

Linux command line print file

Printing from within an application is very easy, selecting the Print option from the menu.

From the command line, use the lp or lpr command.

These commands can read from a pipe, so you can print the output of commands using

There are many options available to tune the page layout, the number of copies, the printer that you want to print to if you have more than one available, paper size, one-side or double-sided printing if your printer supports this feature, margins and so on. Read the man pages for a complete overview.

Once the file is accepted in the print queue, an identification number for the print job is assigned:

> lp /etc/profile request id is blob-253 (1 file(s))

To view (query) the print queue, use the lpq or lpstat command. When entered without arguments, it displays the contents of the default print queue.

> lpq blob is ready and printing Rank Owner Job File(s) Total Size active davy 253 profile 1024 bytes davy:

> lpstat blob-253 davy 1024 Tue 25 Jul 2006 10:20_01 AM CEST

Which is the default printer on a system that has access to multiple printers?

> lpstat -d system default destination: blob

What is the status of my printer(s)?

> lpstat -p printer blob now printing blob-253. enabled since Jan 01 18:01

If you don’t like what you see from the status commands, use lprm or cancel to delete jobs.

In the graphical environment, you may see a popup window telling you that the job has been canceled.

In larger environments, lpc may be used to control multiple printers. See the Info or man pages on each command.

There are many GUI print tools used as a front-end to lp , and most graphical applications have a print function that uses lp . See the built-in Help functions and program specific documentation for more.

Printing on UNIX and alikes has a long history. There used to be two rather different approaches: the BSD-style printing and the SystemV-style printing. For compatibility, Linux with CUPS supports the commands from both styles. Also note that lp does not behave exactly like lpr , lpq has somewhat different options than lpstat and lprm is almost, but not quite, like cancel . Which one you use is not important, just pick the commands that you are comfortable with, or that you may know from previous experiences with UNIX-like systems.

If we want to get something sensible out of the printer, files should be formatted first. Apart from an abundance of formatting software, Linux comes with the basic UNIX formatting tools and languages.

Modern Linux systems support direct printing, without any formatting by the user, of a range of file types: text, PDF, PostScript and several image formats like PNG, JPEG, BMP and GIF.

For those file formats that do need formatting, Linux comes with a lot of formatting tools, such as the pdf2ps , fax2ps and a2ps commands, that convert other formats to PostScript. These commands can create files that can then be used on other systems that don’t have all the conversion tools installed.

Apart from these command line tools there are a lot of graphical word processing programs. Several complete office suites are available, many are free. These do the formatting automatically upon submission of a print job. Just to name a few: OpenOffice.org , KOffice , AbiWord , WordPerfect , etc.

The following are common languages in a printing context:

groff : GNU version of the UNIX roff command. It is a front-end to the groff document formatting system. Normally it runs the troff command and a post-processor appropriate for the selected device. It allows generation of PostScript files.

TeX and the macro package LaTeX : one of the most widely used markup languages on UNIX systems. Usually invoked as tex , it formats files and outputs a corresponding device-independent representation of the typeset document.

Technical works are still frequently written in LaTeX because of its support for mathematic formulas, although efforts are being made at W3C (the World Wide Web Consortium) to include this feature in other applications.

SGML and XML: Free parsers are available for UNIX and Linux. XML is the next generation SGML, it forms the basis for DocBook XML, a document system (this book is written in XML, for instance).

Why are there two commands for every task related to printing?

The man pages contain pre-formatted troff data which has to be formatted before it can roll out of your printer. Printing is done using the -t option to the man command:

man -t command > man-command.ps

Then print the PostScript file. If a default print destination is configured for your system/account, you can just issue the command man -t command to send the formatted page to the printer directly.

Anything that you can send to the printer can normally be sent to the screen as well. Depending on the file format, you can use one of these commands:

PostScript files: with the gv (GhostView) command.

TeX dvi files: with xdvi , or with KDE ‘s kdvi .

PDF files: xpdf , kpdf , gpdf or Adobe’s viewer, acroread , which is also available for free but is not free software. Adobe’s reader supports PDF 1.6, the others only support PDF versions up to 1.5. The version of a PDF file can be determined using the file command.

From within applications, such as Firefox or OpenOffice, you can usually select Print Preview from one of the menus.

Источник

Читайте также:  Windows 2003 панель управления
Оцените статью
Printing documentation