Candidates should should be able to apply filters to text streams. Send text files and output streams through text utility filters to modify the output using standard UNIX commands found in the GNU textutils package.
The following is a partial list of the used files, terms and utilities
cat tac cut expand unexpand fmt head od join nl paste pr sort split tail tr uniq wc
Вопросы по LPI (приблизительные)
Ответы
Фильтрация текста — это процесс преобразований над входным потоком текста до того как он будет выдан в выходной поток. Хотя как входной, так и выходной поток могут поступать из файла, в системах Linux и UNIX фильтрация преимущественно осуществляется через конвейер команд, когда вывод одной команды связывается или перенаправляется на ввод следующей команды.
Интерпретатор оперирует с тремя стандартными потоками ввода/вывода:
stdin это стандартный поток ввода, через который поступает ввод командам
stdout это стандратный выходной поток, через который команды выводят свой выход
stderr это стандартный поток ошибок, через который выводятся ошибки в командах
Конвейер с помощью |
Команды обработки текста (фильтры) могут принимать входной поток, как из стандартного ввода, так и из файла. Чтобы использовать выход команды command1, как входной фильтр command2 вы должны соединить команды с помощью операции конвейерезации (|)
# command1 | command2
Вы можете также использовать | для перенаправления вывода command2 в этом конвейере на вход другой команде, command3. Конструируя длинные конвейеры из команд, каждая из которых выполняет свою задачу, можно понять философию выполнения задач в Linux и UNIX.
# command1 | command2 | command3
Также иногда вы будете видеть знак дефиса (-) вместо имени файла в качестве аргумента команды, в том значении, что ввод будет поступать из stdin, а не из файла.
Перенаправление вывода с помощью >
# echo -e “1 103.1 Work on the command line\n2 103.2 Process text streams using filters\n3 103.3 Perform basic file and directory management” > LPI1
Просмотреть созданный файл можно командой cat. Команда cat принимает ввод из stdin, если вы не определите имя файла
cat (сокращение от catenate – eng. сцеплять, связывать)
# cat LPI1 1 103.1 Work on the command line 2 103.2 Process text streams using filters 3 103.3 Perform basic file and directory management
Создание текстового файла с помощью cat (Используйте комбинацию Ctrl-d чтобы послать сигнал конца файла)
# cat > LPI2 103.4 Use streams, pipes, and redirects 103.5 Create, monitor, and kill processes 103.6 Modify process execution priorities
Соединим (Concatenating) два файла в один
# cat LPI* # cat LPI1 LPI2 1 103.1 Work on the command line 2 103.2 Process text streams using filters 3 103.3 Perform basic file and directory management 103.4 Use streams, pipes, and redirects 103.5 Create, monitor, and kill processes 103.6 Modify process execution priorities
Показывать конец строки опция -E, будет отображаться знак $ в конце строки
# cat -E LPI1 1 103.1 Work on the command line$ 2 103.2 Process text streams using filters$ 3 103.3 Perform basic file and directory management$
Показать номера строк опция -n
# cat -n LPI2 1 103.4 Use streams, pipes, and redirects 2 103.5 Create, monitor, and kill processes 3 103.6 Modify process execution priorities
tac — Unix-утилита, выводящая строки указанных файлов в обратном порядке
# tac LPI1 3 103.3 Perform basic file and directory management 2 103.2 Process text streams using filters 1 103.1 Work on the command line
od — (OctalDump) Unix-утилита, для вывода дампа файла в разных форматах. С разными параметрами, с помощью od можно увидеть содержимое файла в шестнадцатеричном, восьмеричном, десятичном и пр.
od [- опции] [-A в каком формате будет колонка позиций ] [-j начать с какого байта ] [-N длина ] [-t формат вывода ] [файл]
[-A в каком формате будет колонка позиций ] o восьмеричное - по умолчанию d десятичное x шестнадцатеричное n смещения не отображаются
# od LPI1 0000000 020061 030061 027063 020061 067527 065562 067440 020156 0000020 064164 020145 067543 066555 067141 020144 064554 062556 0000040 031012 030440 031460 031056 050040 067562 062543 071563 0000060 072040 074145 020164 072163 062562 066541 020163 071565 0000100 067151 020147 064546 072154 071145 005163 020063 030061 0000120 027063 020063 062520 063162 071157 020155 060542 064563 0000140 020143 064546 062554 060440 062156 062040 071151 061545 0000160 067564 074562 066440 067141 063541 066545 067145 005164 0000200
split — (eng. дробление, расщеплять) Unix-утилита, копирующая файл и разбивающая его на отдельные файлы заданной длины.
Опции команды split
-a, –suffix-length=Н использовать суффиксы длины Н (по умолчанию 2)
-b, –bytes=ЧИСЛО записывать в каждый выходной файл заданное ЧИСЛО байт
-C, –line-bytes=ЧИСЛО записывать не более заданного ЧИСЛА байт из строки
-d, –numeric-suffixes использовать числовые, а не алфавитные суффиксы (по умолчанию алфавитные суффиксы)
-l, –lines=ЧИСЛО записывать в каждый выходной файл заданное ЧИСЛО строк
–verbose печатать сообщение в стандартный поток ошибок перед открытием очередного выходного файла
–help показать эту справку и выйти
–version показать информацию о версии и выйти
Разделим файл LPI3 построчно в файл LPI4
# split -l 1 LPI3 LPI4 # ls LPI4* LPI4aa LPI4ab LPI4ac LPI4ad LPI4ae LPI4af
Разделим большой архив на мелкие части и соберем обратно
# du -sh music.tar.gz 27M music.tar.gz # split -d --suffix-length=4 --bytes=10M music.tar.gz music # du -sh music0* 10M music0000 10M music0001 6,6M music0002 # cat music0* > music2.tar.gz
wc (word count — eng. количество слов) — Unix-утилита, выводящая число переводов строк, слов и байт для каждого указанного файла и итоговую строку, если было задано несколько файлов. Если входной файл не задан, или равен ‘-‘, то данные считываются со стандартного ввода.
Опции команды wc
-c, –bytes напечатать число байт
-m, –chars напечатать число символов
-l, –lines напечатать число переводов строк
-L, –max-line-length напечатать длину наибольшей строки
-w, –words напечатать число слов
–help показать эту справку и выйти
–version показать информацию о версии и выйти
# wc LPI3 6 39 252 LPI3
# wc LPI1 LPI2 LPI3 3 22 128 LPI1 3 17 124 LPI2 6 39 252 LPI3 12 78 504 итого
Посчитать количество срок
# cat /var/log/messages | wc -l 2485
tail Unix-утилита, выводящая несколько (по умолчанию 10) последних строк Опции -c, --bytes=Н показать последние Н байт; или же укажите -c +Н, Популярным использованием tail является слежение за файлом с помощью опции -f, обычно построчно. Это может полезным, если у вас есть фоновый процесс, который генерирует вывод в файл, и вы хотите проверить, что он сделал. В этом режиме tail будет работать, пока вы не прекратите его работу (с помощью Ctrl-c), отображая строки по мере того, как они будут поступать в файл. expand -- (eng. расширить) Unix-утилита, преобразующая символы табуляции в пробелы, сохраняя форматированность текста. expand Unix-утилита, преобразующая пробелы в символы табуляции , сохраняя форматированность текста. tr — (eng. translation) Unix-утилита трансляции (преобразования) символов; используется для отображения определенных символов во входном потоке на заданные символы в выходной поток. [:alnum:] все буквы и цифры Перевести все строчные буквы в заглавные Перевести все строчные буквы в заглавные и отправить в файл LPI5 Удалить все апострофы pr Unix-утилита, которую используют для форматирования файлов перед печатью. nl— UNIX?утилита, выводящая указанный файл на стандартный вывод, добавляя номера строк. fmt -- Unix-утилита, переформатирует каждый абзац в файле(ах) и выводит на стандартный вывод. -w, --width=ЧИСЛО максимальная ширина строки (по умолчанию 75 столбцов) cut (eng. резать) -- Unix-утилита выборки отдельных полей из строк файла -d, --delimiter=РАЗДЕЛИТЕЛЬ использовать для разделения полей РАЗДЕЛИТЕЛЬ вместо табуляции Посмотреть ip адреса со state-ом SYN Посмотреть в очереди qmail кто отправляет сколько писем Показать логины пользователей Вырезать ip eth0 из вывода ifconfig eth0 paste (eng. склеивать) -- Unix-утилита, которая принимает два или несколько файлов в качестве входных данных, объединяет построчно и выводит результат. Может быть удобно для создания таблиц или колонок текста. Опции join (eng. присоединить) -- Unix-утилита, объединяющая строки двух упорядоченных текстовых файлов на основе наличия общего поля. sort -- Unix-утилита, выводящая сортированное слияние указанных файлов на стандартный вывод с использованием установленной в среде локали. Опции uniq -- Unix-утилита, с помощью которой можно вывести или отфильтровать повторяющиеся строки в файле. Опции Посчитаем IP адреса которые обратились к favicon Вопросы по LPI (приблизительные)
# tail /var/log/messages
Feb 24 10:12:42 bezha kernel: [ 48.632319] cdrom: sr0: mrw address space DMA selected
Feb 24 10:13:12 bezha kernel: [ 78.541234] lo: Disabled Privacy Extensions
Feb 24 10:13:48 bezha kernel: [ 115.008526] Clocksource tsc unstable (delta = -202156502 ns)
Feb 24 10:41:14 bezha rsyslogd: [origin software="rsyslogd" swVersion="4.2.0" x-pid="873"]
Feb 24 11:18:01 bezha kernel: [ 3967.817899] lo: Disabled Privacy Extensions
Feb 24 11:18:27 bezha sudo: pam_sm_authenticate: Called
Feb 24 11:18:27 bezha sudo: pam_sm_authenticate: username = [bezha]
Feb 24 11:33:05 bezha kernel: [ 4871.531303] lo: Disabled Privacy Extensions
Feb 24 12:19:45 bezha kernel: [ 7671.777618] lo: Disabled Privacy Extensions
Feb 24 12:38:22 bezha kernel: [ 8788.684416] lo: Disabled Privacy Extensions
-f, --follow[={name|descriptor}] выводить поступающие данные по мере роста файла;
-n, --lines=Н выводить последние Н строк, а не последние 10;
-q, --quiet, --silent не выводить заголовки с именами файлов
-s, --sleep-interval=С с ключом -f, спать между итерациями примерно С секунд (по умолчанию 1.0)
-v, --verbose всегда выводить заголовки с именами файлов
--help показать эту справку и выйти
--version показать информацию о версии и выйти
# tail -f /var/log/messages
tr [options] SET1 [SET2]
[:alpha:] все буквы
[:blank:] все горизонтальные пробельные знаки
[:cntrl:] все управляющие знаки
[:digit:] все цифры
[:graph:] все печатные знаки, исключая пробел
[:lower:] все строчные буквы
[:print:] все печатные знаки, включая пробел
[:punct:] все знаки препинания
[:space:] все вертикальные или горизонтальные пробельные знаки
[:upper:] все заглавные буквы
[:xdigit:] все шестнадцатеричные цифры
[=ЗНАК=] все знаки, эквивалентные ЗНАКУ
tr "[:lower:]" "[:upper:]" < LPI1
103.1 WORK ON THE COMMAND LINE
103.2 PROCESS TEXT STREAMS USING FILTERS
103.3 PERFORM BASIC FILE AND DIRECTORY MANAGEMENT
# tr "[:lower:]" "[:upper:]" < LPI1 > LPI5
# echo "W'ORK O'N THE C'OMMAND L'INE" | tr -d \'
WORK ON THE COMMAND LINE
# pr LPI3 | head
2011-02-23 19:11 LPI3 Страница 1
1 103.1 Work on the command line
2 103.2 Process text streams using filters
3 103.3 Perform basic file and directory management
103.4 Use streams, pipes, and redirects
103.5 Create, monitor, and kill processes
# pr -d LPI3 | head
2011-02-23 19:11 LPI3 Страница 1
1 103.1 Work on the command line
2 103.2 Process text streams using filters
3 103.3 Perform basic file and directory management
# nl LPI2 | pr | head
2011-02-24 14:41 Страница 1
1 103.4 Use streams, pipes, and redirects
2 103.5 Create, monitor, and kill processes
3 103.6 Modify process execution priorities
# fmt -w 50 LPI1
103.1 Work on the command line 103.2 Process
text streams using filters 103.3 Perform basic
file and directory management
-f, --fields=СПИСОК выбрать только заданные поля
# netstat -na | grep SYN | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n
# qmHandle -s -l | grep "Return-path" | awk '{print $2}' | cut -d: -f1 | sort | uniq -c | sort -n
# cut -d: -f1 /etc/passwd
# ifconfig eth0 | grep "inet addr" | cut -d: -f 2 | cut -d\ -f 1
paste [-s] [-d разделитель] file
[-s] — меняет положение строк со столбцами
[-d разделитель] — меняет разделитель на указанный
# paste LPI1 LPI2
103.1 Work on the command line 103.4 Use streams, pipes, and redirects
103.2 Process text streams using filters 103.5 Create, monitor, and kill processes
103.3 Perform basic file and directory management 103.6 Modify process execution priorities
# cat LPI1 LPI2
1 Work on the command line
2 Process text streams using filters
3 Perform basic file and directory management
1 Use streams, pipes, and redirects
2 Create, monitor, and kill processes
3 Modify process execution priorities
# join LPI1 LPI2
1 Work on the command line Use streams, pipes, and redirects
2 Process text streams using filters Create, monitor, and kill processes
3 Perform basic file and directory management Modify process execution priorities
-b, --ignore-leading-blanks игнорировать начальные пропуски
-d, --dictionary-order рассматривать только пропуски, буквы и цифры
-f, --ignore-case игнорировать регистр букв
-g, --general-numeric-sort сравнивать в соответствии с общим числовым значением
-i, --ignore-nonprinting рассматривать только печатные символы
-h, --human-numeric-sort сравнивать числа в удобном для человека виде (например, 2K 1G)
-n, --numeric-sort сравнивать числовые значения строк
-R, --random-sort сортировать по случайным хэш-числам ключей
-r, --reverse обратить результаты сравнения
-V, --version-sort сортировать по номерам (версии) в текстовом представлении
# ls | sort
Dropbox
LPI1
LPI2
LPI3
LPI5
Music
Unix
clock_rings.lua
popcorn
Загрузки
Рабочий стол
Необходимо отсортировать список на входе.
-c, --count выводить число повторов в начале каждой строки
-d, --repeated выводить только повторяющиеся строки
-D, --all-repeated[=delimit-method] напечатать все повторяющиеся строки
-f, --skip-fields=Н не сравнивать первые Н полей
-i, --ignore-case игнорировать регистр при сравнении
-s, --skip-chars=Н не сравнивать первые Н символов
-u, --unique выводить только неповторяющиеся строки
-z, --zero-terminated строки оканчиваются байтом с 0, а не символом новой строки
-w, --check-chars=Н сравнивать первые Н знаков строк
--help показать эту справку и выйти
--version показать информацию о версии и выйти
# grep favicon /var/log/apache2/access.log | awk '{print $1}' | sort | uniq -c
1. Which tool would be used to add line numbers to a file?
2. Which tool allows two files to be combined using fields?
3. Which utility is used to create lines of a specified length inside a file?
4. Which utility is used to view a file in reverse?
5. Which utility allows you to delete characters from a file?
6. Which utility allows files to be viewed in hexadecimal format?
7. Which utility is used to alphabetize the contents of a file?
8. Which command would separate the file researchpaper into multiple files,
each containing 60 lines? (Select all that apply.)
A. split -60 researchpaper
B. split -C 60b researchpaper
C. split -C 60 researchpaper
D. split -l 60 researchpaper
9. Which utility is used to combines the lines from two files? (Select all that apply.)
A. split
B. join
C. paste
D. cut
10. Which of the following would be used to view the last five lines of the file myfiles?
A. tac myfiles
B. tail myfiles
C. tac -5 myfiles
D. tail -5 myfiles
11. Which of the following allows you to view the file myfiles in octal format?
(Select all that apply.)
A. od myfiles
B. od -t o myfiles
C. od -t x myfiles
D. od -o myfiles
12. The ___________ utility is used to view a file in reverse.
13. Which utility is used to provide a total count of all lines in a file?
A. nl
B. ln
C. wc
D. tr
14. The ____________ utility is used to ensure that files appear the same, regardless
of the system used to view them, by changing tabs to spaces.
15. Which utility attempts to create lines of equal length throughout a file?
A. nl
B. ln
C. fmt
D. expand
16. Which utility would be easily used to replace all lowercase letters in a file with
uppercase letters?
A. cut
B. sed
C. tac
D. tr
17. Which of the following is used to verify that a file is alphabetized?
A. sort -c
B. sort -d
C. sort -v
D. sort -m
18. What program would you use to display the end of a configuration file?
A. uniq
B. cut
C. tail
D. wc
19. What is the effect of the following command? $ pr report.txt | lpr
A. The file report.txt is formatted for printing and sent to the lpr program.
B. The files report.txt and lpr are combined together into one file and sent to standard output.
C. Tabs are converted to spaces in report.txt, and the result is saved in lpr.
D. None of the above
20. Which of the following commands will number the lines in aleph.txt? (Select all that apply.)
A. fmt aleph.txt
B. nl aleph.txt
C. cat -b aleph.txt
D. cat -n aleph.txt
21. You’ve received an ASCII text file (longlines.txt) that uses no carriage returns within
paragraphs but two carriage returns between paragraphs. The result is that your preferred
text editor displays each paragraph as a very long line. How can you reformat this file so
that you can more easily edit it (or a copy)?
A. sed ‘s/Ctrl-M/NL/‘ longlines.txt
B. fmt longlines.txt > longlines2.txt
C. cat longlines.txt > longlines2.txt
D. pr longlines.txt > longlines2.txt
1. nl
2. join
3. fmt
4. tac
5. tr
6. od
7. sort
8. The correct answer is A, D.
The -l option is used to specify the number of lines contained in
each file using split. However, when no option is given the number specified
is assumed to be the number of lines.
9. The correct answer is B, C.
The paste and join utilities are used to combine lines from a file.
The split command is used to divide a file into multiple pieces. cut removes
text from a file.
10. The correct answer is D.
The tail command is used to view the end of a file and the -5 option specifies
the number of lines to view.
11. The correct answer is A, B.
The od utility is used to view files in octal format by default. The -t option, followed by o,
is used to specify octal format.
12. tac. The tac utility is used to view a file starting at the last line and ending with
the first.
13. The correct answer is C.
The wc utility is used to provide totals of a file including word count, line
count, and byte count.
14. expand. The expand utility is used to convert tab characters to spaces.
15. The correct answer is C.
The fmt utility attempts to create lines of equal length throughout a file.
16. The correct answer is D.
The tr utility is used to delete and replace characters in a file.
17. The correct answer is C.
Use the -c option with the sort utility to verify that a file has been sorted.
18. The correct answer is C.
The tail command displays the final 10 lines of a file.
The uniq command removes duplicate lines from a list.
The cut command echoes the specified characters or fields from an input text file.
The wc command displays counts of the number of characters, words, and lines in a file.
19. The correct answer is A.
The pr program takes a text file as input and adds formatting features intended for
printing, such as a header and blank lines to separate pages. The command also pipes the
output through lpr (which is a Linux printing command).
20. The correct answer is B, C, D.
The nl command numbers lines, so it does this task without any special options.
The cat command can also number lines via its -b and -n options;
-b numbers non-blank lines,
-n numbers all lines (including blank lines).
The fmt command is the only one described here that will not number the lines of the input file.
21. The correct answer is B.
The fmt command performs the desired task of shortening long lines by inserting carriage returns.
It sends its results to standard output, so option B uses output redirection to
save the results in a new file.
The sed command of option A won’t accomplish anything useful; it only replaces the string Ctrl-M with
the string NL. Although these strings are both sometimes used as abbreviations for carriage returns
or new lines, the replacement of these literal strings isn’t what’s required.
Option C creates an exact copy of the original file, with the long single-line paragraphs intact.
Although option D’s pr command is a formatting tool, it won’t reformat individual paragraphs.
It will also add headers that you probably don’t want.