- lpr: печать из командной строки
- В Debian/Ubuntu:
- В Fedora/Cent OS/RedHat:
- Команда lpr:
- Список сетевых принтеров:
- Печать на заданный принтер:
- Проверка состояния:
- Очистка очереди печати:
- Печать всех файлов в директории:
- Печать из командной строки Linux
- Вывод параметров принтера
- Полезные команды
- Двусторонняя печать
- Печать в ландшафтном режиме
- How to Print files in Linux Using Command Line
- How to Print using pr command?
- How to Print using lp/lpr command?
- Check and Abort file printing using lpstat and cancel command
- How can I display the contents of a text file on the command line?
- 8 Answers 8
- Using cat
- Using less
- Using od
- 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), либо поместите имя в кавычки, либо начните вводить имя файла и нажмите клавишу табуляции, чтобы вызвать завершение файла (как показано во втором примере ниже).
Команда 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.
Why are there two commands for every task related to printing? |
---|
Printing documentation |
---|