ОБРАБОТКА ТЕКСТА

КОРОТКОЕ ВВЕДЕНИЕ

Что такое обработка текста?

По моему скромному мнению, в предыдущем блоге я уже начал изучать обработку текста, которая обрабатывает вывод в формате текст в вывод, который мы хотим см. (вы понимаете, о чем я, да? Типа мы используем не всю информацию вывода, а только часть). В этом блоге я расскажу о других инструментах, которые можно использовать для обработки текста.

Почему мы этому учимся?

Эта штука облегчит нам поиск текста или информации на основе данных, которые мы получаем на выходе.

КОМАНДЫ

РЕЗАТЬ

Если вы когда-либо программировали на Java или C (язык программирования), вы слышали о «подстроке». Если вы когда-либо компилировали данные в Microsoft Excel, вы слышали о «Mid()». Нах этот такой.

Мы можем использовать его как для файлов, так и для команд.

Column 1: CUT Command.
Format
cut [args] [file]
cut -c1 filename
//C is for character, so this will cut the text in a file, 1 char at each row
cut -c1,2,4 filename
//This one will cut the text in a file and take only char 1, 2, and 4 for each row
cut -c1-3 filename
//This one will cut the text in a file and take char from 1 to 3 for each row
cut -c1-3,6-8 filename
//Merge char from 1 to 3 and 6 to 8 in a file for each row
cut -b1-3 filename
//B is cutting by byte size, basically it is the same as using C
cut -d: -f 6 filename
//D is for delimiter, so everything comes after D will be a delimiter that acts a splitter. Before and after that symbol will be treated as "field". So you have to declare -f to choose which field that will be the output
cut -d: -f 5-7 filename
//It is the same as before but this time we choose from field 5 to 7
ls -ltr / | cut -d ' ' 2 filename
//If the sample before cut text from file, this one is cutting from command

АВК

Обозначает имя авторов этой команды. Кто, Вайнбергер, Керниган. Это немного сложнее, чем cut, но обладает уникальными возможностями с точки зрения обработки текста. Его также можно использовать для поиска текста, размера текста и других параметров.

Column 2: AWK Command.
Format
awk [args] [file]
awk '{print $1}' filename
//It will print column 1 of the content of the file
ls -l | awk '{print $1,$3}'
//Will only print column 1 and 2 from ls command
ls -l | awk '{print $NF}'
//Will only print the last column from ls command
awk '/Jerry/ {print}' filename
//Will search a word 'Jerry' in the directory listed and print its row
awk -F: '{print $1}' /etc/passwd
//Output only 1st field of /etc/passwd, F is like a field with : as delimiter.
echo "Hello Tom" | awk '{$2="Sayful"; print $0}' 
//Replace words field word and print out the row
cat filename | awk '{$1="Sayful"; print $0}'
//Replace words field word in a file and print out the row
awk 'length($0)>15' filename
//Will search the lines that have more than 15 bytes long
ls -l | awk '{if($9 == "Sayful") print $0;}'
//Will search matching "Sayful in the PWD
ls -l | awk '{print NF}'
//Will print the number of fields present in this command each row

ГРЭП/ЕГРЭП

Знакомы ли вы с Regex? В Nah Linux есть два инструмента, связанных с Regular Expression.
GREP означает Global Regular Expression Print,
EGREP означает Extended GREP. сильный>.

Column 3: GREP and EGREP commands
grep [keyword] [file]
//Search a keyword from a file
grep -c [keyword] [file]
//Count total keywords present from a file
grep -i [keYWoRd] [file]
//Search a keYWoRd with ignoring uppercase & lowercase
grep -n [keyword] [file]
//Search a keyword from a file include which line it is
grep -v [keyword] [file]
//display everything but keyword
grep [keyword] [file]  | awk '{print $1}'
//Search a keyword from a file but only return the first field
[command] | grep -i [keyword]
//Search keYWoRd from the output of the command with ignoring cases.
egrep -i "keYWorD1|KeYwORd2" [file]
//Search keYWorD1 or KeYwORd2 in a file

Поэтому, если вы хотите выполнить поиск по более чем одному ключевому слову, вы можете использовать egrep. Также вы можете поместить вывод первого GREP во второй GREP.

СОРТИРОВАТЬ/УНИКАЛЬНО

СОРТИРОВКА, я думаю, вы знаете это и без меня. Он сортирует вывод в алфавитном или числовом порядке. Вы также можете выбрать, какое поле вы хотите использовать в качестве базы для сортировки.

UNIQ, вот это, вы поняли, верно? Это удалит дублированные элементы выходов. Сказали, что для «Иеремии» есть более одной строки вывода, угадайте, как система покажет это, когда мы запустим команду UNIQ? Верно, будет показан только ОДИН «Иеремия». Но помните, что сначала вы должны использовать SORT, а затем использовать PIPE для использования этой команды. Потому что эта команда не удалит повторяющиеся элементы, когда они разнесены друг от друга.

Column 4: SORT and UNIQ commands
sort [filename]
//Will sort the contents of the file based on "each line"
sort -r [filename]
//Will sort the contents in reversed order
sort -k2 [filename]
//Will sort the contents of the file based on field number 2
[commands] | sort [args]
//Will sort the output of command based on argument given
----------------------------
uniq [filename]
//Will remove duplicated output based on "each line", please notes, if the duplicated is not in 1-line different, then the duplicated items will not be removed
sort [filename] | uniq
//Will sort the contents of the file and remove the duplicated items
[commands] | sort [args] | uniq -c
//Will sort the output of the command, sort it based on the arguments given, show only uniq line (items), and will count how many duplicated items each line (items)

WC

Подсчет слов, он будет подсчитывать слова, написанные в команде или файлах.

Column 5: WC command
wc [filename]
//Check the line count, word count, and byte count
wc -l [filename]
//Get the number of lines in a file
wc -w [filename]
//Grab the number of words in a file
wc -c --bytes [filename]
//Pick the number of bytes in a file
wc [directory]
//not allowed, because there is no content inside
ls -l | wc -l
//count the files
grep [keywords] | wc -l
//count the keyword lines on a file or commands.

ВЫВОДЫ

На сегодня это все, я изучаю удивительные команды в Linux. Я думал, что Linux будет так сложно понять, но нет! Линукс делают группы людей. Значит они люди, я тоже! Итак, я должен быть в состоянии изучить эту вещь!

Увидимся в следующий раз!

                     Read more of my stories Here!
< My Previous Blog                                    My Next Blog >