Linux text processing commands
Regular Expression
POSIX standard classifies regular expressions into two types
1. Basic Regular Expression
2. Extended Regular Expressions
Most Linux applications and tools only support basic regular expressions.
Basic Regular Expression
| Symbol |
Meaning |
| * |
0 or multiple characters |
| . |
Match any character |
| ^ |
The beginning of the line, which is not in [] |
| $ |
End of line |
| [] |
Matching Character Set combination |
| \ |
Escape characters |
| \ <\> |
Exact match symbol |
| \ {N \} |
Match n times |
| \ {N ,\} |
Match at least n times |
| \ {M, n \} |
Matching m ~ N times |
Extended Regular Expression
| Symbol |
Meaning |
| ? |
Match 0 or 1 |
| + |
Match one or more |
| () |
Indicates that a character set is combined or used in expr. |
| | |
Represents or |
Wildcard
Bash Shell itself does not support regular expressions. It uses shell commands and tools such as grep, AWK, and sed. However, bash Shell can use some metacharacters in regular expressions for wildcard configuration.
| Symbol |
Meaning |
Example |
Explanation |
| * |
Any character |
Phi * ip. rtf |
Files starting with Phi and ending with ip. rtf |
| ? |
Any character |
Ls-l 0 ?. Pem |
List pem files starting with 0 and with two characters |
| [] |
Range |
Ls-l [a-h]. awk |
List awk files starting with a-h |
| {} |
A combination of expressions |
Ls-l {[a-h] *. awk, 0 ?. Pem} |
Match [a-h] *. awk or 0 ?. Pem File |
| ^ |
Invert |
Ls-l [a-h] *. [^ awk] * |
Files starting with a-h and not awk type |
Grep
Search for Regular expressions and Print the rows (Global search Regular Expression and Print out the line)
Grep [Option] [mode] [file…]
Option
| Option |
Meaning |
Entire word |
| -C |
Only the number of matched rows is output. |
Count |
| -I |
Case Insensitive during search |
Ignore |
| -H |
When querying multiple files, the file name is not displayed. |
|
| -L |
Only names of matching files are listed, not specific matching rows. |
List |
| -N |
Lists All matched rows and displays row numbers. |
Number |
| -S |
Do Not Display error messages that do not exist or do not match the text |
|
| -V |
Show all rows that do not contain matched text |
Reverse |
| -W |
Match the entire word |
Word |
| -X |
Match the entire line |
|
| -R |
Recursive search not only searches for the current working directory, but also subdirectories |
Recursion |
| -Q |
No output is allowed. Exit indicates whether the search is successful. |
Quit |
| -B |
Print the offset of the header of the matching line spacing file, in bytes |
Byte |
| -O |
Used in combination with the-B Option to print the offset of the matching word from the file header, in bytes |
|
| -E |
Extended Regular Expressions |
Extract |
| -F |
Regular expressions are not supported. Matching is performed based on the literal meaning of the string. |
|
Mode
String, variable, and regular expression
Note: As long as the mode contains spaces, you need to use double quotation marks to introduce the mode.
Instance-w and-x options
The grep command mode supports regular expressions. The metacharacters of regular expressions are interpreted as special meanings;
-W indicates that the entire word is matched, that is, it is interpreted using the literal meaning of the pattern.
For example:
Grep cer **. pem
Grep-w cer **. pem
-X indicates matching the entire row.
-W is inconvenient to use. It is best to use grep with-F.
Standard grep command, supporting basic regular expression egrep
Extended grep command, supporting basic and extended Regular Expressions
Equivalent to grep-E fgrep
The quick grep command does not support regular expressions and matches them by literal meaning.
Equivalent to grep-Fsed
Sed, stream editor, and stream editor. They apply a series of editing commands to a batch of text files.
Applicable scenarios:
The file editing commands that are too large for the interactive editor are too complex to scan files if they are difficult to input in the interactive text editor. However, you need to execute multiple editing functions.
Three call Methods
Sed [Option] 'sed command 'input file sed [Option]-f sed script input file./sed script file input file option
| Option |
Meaning |
| -N |
Do not print all rows to standard output |
| -F |
The sed script file is being called. |
| -E |
Parses the Next string into a sed edit command. If only one edit command is passed to sed, You can omit-e |
Sed command
Usually consists of the positioning text line and the sed editing command. The sed Editing Command performs various processing on the positioning text line.
Sed locates text lines
| Option |
Meaning |
| X |
X indicates the specified row. |
| X, y |
Specify row range |
| /Pattern/ |
Rows in the include Mode |
| /Pattern/ |
Contains rows in two modes |
| /Pattern/, x |
Rows from matching rows with pattern to x |
| X,/pattern/ |
Matching rows from x to pattern |
| X, y! |
Rows excluding x and y |
Sed edit command
The sed editing command indicates the processing of text, such as printing, deleting, appending, inserting, and replacing the text.
| Option |
Meaning |
| P |
Print matching rows |
| = |
Print the file line number |
| D |
Delete row |
| A \ |
Append text after locating the row number |
| I \ |
Insert text before locating a row number |
| C \ |
Use new text to replace and locate text lines |
| S |
Replace the corresponding mode with the replacement mode. |
| R |
Read text from another file |
| W |
Write text to another text |
| Y |
Character conversion |
| Q |
Exit after the first pattern match is complete. |
| L |
Display control characters equivalent to octal ASCII code |
| {} |
Locate the Command Group that the row executes |
| N |
Read the next input line and use the next command to process the new line. |
| H |
Copy the text in the mode buffer to keep the buffer |
| H |
Append the text in the mode buffer to the keep buffer. |
| X |
Swap mode buffer and keep buffer |
| G |
Copy the reserved buffer text to the mode Buffer |
| G |
Append the buffer text to the mode Buffer |
Instance sed-n '1p' file sed-E'/^ f */p'-E'/^ f */= 'file location command
Match metacharacters
Sed-n'/./P' input
Sed-n'/$/P' input uses metacharacters for matching
Sed-N' P' input (note: Indicates the last line in the sed command)
Sed-n'/^ $/P' input (matches empty rows)
Sed-n'/. * bus/P' input! Symbol
Sed-n'2, 10! P'input uses the row number and keyword match to limit the row range
Sed-n'/seugrid/, $ P' input
Sed-n'3,/seugrid/P' input
Edit command
Insert text
Sed 'specify address I \ text' input (inserted before specified location)
Sed 'specify address a \ text' input (insert after specified location)
Sed '/I \ input \ nsecond' (insert two rows of input and second)
Sed '/I/a \ input \ nsecond' Modify text
Sed 'specify the address c \ text' input (change the entire matching row to a new text line)
Sed '/Certificate/c \ New line:' input to delete text
Sed 'specify location d' input (delete specified row) to replace text
Sed's/replaced string/New String/[replacement option]'
Sed's/replaced string/New String/number [replacement option] '(number (1 ~ 512) times matching)
| Option |
Meaning |
| G |
Replace all |
| P |
Combined with the-n option, only replace rows are printed. |
| W file name |
Directs the output to a file. |
Write New File
Sed 'specify address w file' input
Sed '1, 5 w file' input
Sed '/Certificate/w file' input reads text from the file
Sed 'specify address r file' input exit command
Sed 'specify address Q' input conversion command
Sed 'y/replaced Character Sequence/transformed Character Sequence/'input file
The two sequences must have the same length.
Sed 'y/fmg/FMG/'input display control characters
Display the Escape Character, F1 key, shift key, etc.
Sed-n l input
Sed-n 'specify location l' input Execute Command Group in the positioning line
Sed-n-e '/Certificate/p'-e'/Certificate/= 'input
Sed-n'/Certificate/{p; =} 'input advanced editing command
Process the next row of the matched row
Sed '/Certificate/{n; s/11/99/;}' processing of the input sed Buffer
Sed '/Subject/h;/seugrid/x; $ G' input
1. Match the Subject and write the matched row into the buffer.
2. Match the seugrid to ensure the buffer and mode buffer exchange.
3. To the end line, append the buffer to the mode buffer using semicolons to separate multiple editing commands
The preceding example uses AWK.
The basic syntax of awk is similar to that of C language. Similar to sed, awk is used to process text. awk can browse and extract information from a file or string based on specified rules, to perform other text operations
The latest awk is gawk, which allows you to find data, extract data from files, and create pipeline flow commands.
AWK Programming Model
The awk program is maintained by a main input loop. The main input loop automatically reads the file row in sequence, processes the action of the file row as defined by the programmer, and executes the statement cyclically until the condition is terminated.
Different from C, C ++, and Java, a programmer does not need to focus on opening a file, reading a file row, and closing the file, but only on the execution of the processing row.
AWK calls in Shell
Awk [-F domain separator] 'awk program Block' input file inserts awk program Block' into the script file
Awk-f awk script file input file sets the script file to Executable
./Awk script file input file AWK programming AWK mode match
Awk consists of modes and actions. The mode is a set of statements used to test whether the input row needs to execute the statement. The action is the execution process of statements, functions, and expressions. That isThe Mode determines when an action triggers an event, and the action is executed to process the input row.
For example: awk '/^ $/{print "this is a blank line."}' input
Records and Domains
Awk considers the file to be structured. Each row is a record and the record is composed of fields. spaces, tabs, and other symbols are used to separate the fields.
Domain operator $: Specifies the domain of the action to be executed, $1... Identifies each field. $0 indicates the entire record. It can also be used with variables or variable expressions.
For example: awk 'in in {one = 1; two = 2} {print $ (one + two)} 'input
The default value is space. The Tab key is considered to be multiple spaces (or multiple spaces are considered as one space)
1. You can use-F to change the default delimiter.
2. You can use the environment variable FS to set the delimiter.
Instance:
1. FS = "\ t"
2. FS = "\ t +"
Record: waz \ t \ tcq
For FS = "\ t", it is divided into three domains: waz, airspace, cq; for FS = "\ t +", the result is waz, cq
Relational and boolean operators
| Operator |
Meaning |
| < |
|
| > |
|
| ... |
... |
| ~ |
Match Regular Expression |
| !~ |
Do not match Regular Expression |
| Ll |
|
| && |
|
| ! |
|
Instance: Test ~ Operator awk 'in in {FS = ":"} $1 ~ /Root/'input awk Condition Statement
Similar to C, if, if/else, if/else
Awk 'im im {FS = ":"} {if ( 1/root/) print 0} 'passwd expression
Supports addition (+), subtraction (-), multiplication (*), Division (/), modulo (%), multiplication (^ Or **), auto-increment (++ x, x ++)
An expression can be composed of numeric values, character constants, variables, operators, functions, and regular expressions.
Instance
1. count the number of blank rows
Awk '/^ $/{x + = 1} END {print x}' input
2. Calculate the average score
Awk 'in in {FS = ","} {total = 4 + 5 + 6 + 7; avg = total/4; print $1, avg} 'input
System Variables
| Variable |
Meaning |
| $ N |
The Nth domain of the current record, separated by FS |
| $0 |
All recorded Domains |
| FS |
Field separator, default Space |
| RS |
Record separator, line feed by default |
| NR |
Number of current records |
| NF |
Number of domains in the current record |
| OFS |
Output domain separator, default Space |
| ORS |
Output record separator, line feed by default |
| FILENAME |
Current file name |
| ARCC |
Number of command line parameters |
| ARGIND |
Position of the current file in the command line (starting from 0) |
| ARGV |
Command Line Parameter Array |
| Convemts |
Digital Conversion format |
| ENVIRON |
Environment Variable Association Array |
| ERRNO |
Last system error description |
| FILEDWIDTHS |
Field width list, separated by Space key |
| FIR |
Number of browsing file records |
| IGNORECASE |
Boolean variable. If true, case-insensitive matching is performed. |
| OFMT |
Number output format |
| RLENGTH |
String Length matched by the match Function |
| RSTART |
The first position of the string matched by the match Function |
| SUBSEP |
Array subscript separator. Default Value: \ 034 |
Format output
A major feature of awk is to generate reports, which must be formatted and output according to the predefined format.
Printf (format controller, parameter)
| Modifier |
Meaning |
| - |
Left aligned |
| Width |
Domain step size |
| . Prec |
Number of digits to the right of the decimal point |
| 0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
| Format character |
% C |
% D |
% E |
% F |
% O |
% X |
% S |
Built-in string functions
| Function Name |
Meaning |
| Gsub (r, s) |
Replace r with s in the input file. The scope is $0. |
| Gsub (r, s, t) |
Replacing r with s in t can act on a domain $ n |
| Index (s, t) |
Returns the position of the first t of the string in s. |
| Length (s) |
Returns the length of s. |
| Match (s, t) |
Test whether s contains a string that matches t |
| Split (r, s, t) |
Use t to separate r, generate array s, and generate the number of elements in the array |
| Sub (r, s, t) |
Replace the r that appears for the first time in t with s. |
| Substr (r, s) |
Returns the suffix starting from s in string r. |
| Substr (r, s, t) |
Returns the suffix of string r starting from s and ending with t. |
Instance awk 'in in {FS = ":"; OFS = ":"} gsub (/root/, "gridsphere", $1) 'input awk' BEGIN {FS = ": "; OFS =": "} gsub (/root/," gridsphere ") {print $0} 'input awk' BEGIN {print index (" gridsphere ", "ph")} 'awk' BEGIN {print length ("gridsphere")} 'awk' BEGIN {print match ("hello",/h. */)} 'pass parameters to the awk script
Variables in the awk script can be assigned values in the command line to implement parameter transfer in the awk script. The value assignment is placed after the script and before the input file, as shown in
Awk script parameter = value input file
The parameters passed by awk can be custom or system variables.
Conditional and cyclic statements
If () Action 1 [else Action 2]
While () Action
Do action while ()
For () Action
Array
Array [index] = value
1. Join an array
The associated array is the index of the index group. It can be a string or a number.
The values of the correlated arrays do not need to be stored as consecutive addresses.
All arrays of awk are associated arrays. The numeric index used does not represent the array storage address information.
Access array:
For (variable in array) do something with array [variable]
Determine whether an element exists in the array
If (index in array) do
2. split Function
Split (r, s, t): splits the r string into a String Array Using t as the separator and stores it in s.
Awk 'in in {print split ("abc/def/ghi", str, "/"); for (I in str) print str [I]}'
Text Processing Command
Text processing Commands include sorting of file records and merging and separation of files. Specific commands: sort, uniq, join, cut, paste, split, tr, and tar. These commands enable sorting, statistics, merging, extraction, pasting, separation, filtering, compression, and decompression of file records. With sed, awk constitutes all the commands and tools for Linux Text Processing
Sort
Rt: sorts files. The input file is considered as a data stream composed of multiple records, and the record is composed of Variable-width fields ., Line breaks are used as delimiters. Like awk, the sort command can divide records into multiple domains for processing. The default domain Delimiter is a space character.
Sort [Option] [input file]
| Option |
Meaning |
| -C |
Test whether the files have been sorted |
| -K |
Specify the sorted domain |
| -M |
Merge two sorted files |
| -N |
Sort by number size |
| -O [output file] |
Writing the output to the specified file is equivalent to redirecting the output to the specified file. |
| -R |
Reverse display of sorting results |
| -T |
Change domain Separator |
| -U |
Remove duplicate rows in the result |
Sort-t: input sort-t:-k3 input sort-t:-k3n input
-N is generally not used independently. It is generally placed after the domain number sort-t:-k3nr input sort-t:-u input sort-t:-k3n-o output input sort-t: -c input sort-t:-m input1 input2
Input1 and input2 must be ordered uniq
Removes consecutive duplicate rows in a text file, similar to sort-u.
| Option |
Meaning |
| -C |
Only print the number of times that each row repeats in the text. |
| -D |
Only records with duplicates are displayed. Each duplicate record appears only once. |
| -U |
Show only records with no duplicates |
Number of words in the Statistical File
Cat input | sed's /. // g; s/= // g; s/, // g; s/\ // g; s // \ n/g; s/\ t/\ n/G' | sed '/^ $/d' | sort | uniq-c | sort-nr
Join
The connection operation selects records with the same domain in the two files and places all these records in one row (including all the domains from the two files)
Note: The file must be ordered.
| Option |
Meaning |
| -A1 or-a2 |
In addition to displaying the results of connection with a common domain,-a1 indicates that records with no common domain exist in the first file, and-a2 indicates that records with no common domain exist in the second file. |
| -I |
Case sensitivity differences are ignored when domain content is compared. |
| -O |
Set the format of the Result Display |
| -T |
Change domain Separator |
| -V1 or-v2 |
Similar to-a, but the result of connection with a common domain is not displayed |
| -1 and-2 |
-1 is used to set the connection domain of file 1 and-2 is used to set the connection domain of file 2. |
Join [Option] file1 file2
A bit like join in SQL
Join-t: teacher. db teacher_hobby.db
By default, the first domain is compared, and the connection is equal. -A is a bit like a left outer connection and a right outer connection.
-A1 left join-a2 right join-o indicates to display those fields (SQL fields)
-O1.n 2.n-I ignore case-t set the domain separator-v to reverse, that is, do not display the common domain
Similar to-a,-v1-v2-1,-2 indicates the domain instance to be connected.
For connections from multiple domains, use awk
Awk'
// (NR indicates the number of records read, and FNR indicates the number of records in the current file. Only the first file can make NR \ = FNR)
NR = FNR
{
A [$1 FS $2] = $0;
// Equivalent to break. The processing of this line is complete and the next line is processed.
Next;
}
// When it is finally executed here, a stores records in file 1
// When $1 FS $2 of file 2 is in file a, the two lines of the two files are the same
$1 FS $2 in
{
// Store records with the same columns in B
B [FNR] = a [$1 FS $2] FS $3
}
END
{
// Print
// The array in awk is an associated array.
For (I = 1; I <= FNR; I ++)
If (I in B)
Print B [I]
}'
Test1 test2
Cut
The cut command is used to extract text from standard input or text files by field or line
| Option |
Meaning |
| -C |
Specifies the number or range of extracted characters. |
| -F |
Specify the number of extracted domains or domain range |
| -D |
Change domain Separator |
-C extract text by character
Cut-c2 input
Cut-c1, 5 input (extract 1st and 5th characters)
Cut-C1-5 input (extract 1 ~ 5)-f extract text by field-d similar to-tpaste in sort and join
It is used to paste content from a text file or standard output to a new file. It can paste data from different files together to form a new file. If the number of lines in the two files is different, the missing one is null.
Paste [Option] File 1 file 2...
| Option |
Meaning |
| -D |
The default domain separator is space or Tab key, and the new domain separator is set. |
| -S |
Paste each file into a line |
| - |
Read data from standard input |
Split
This command is used to cut a large file into a small file. The split command can cut the file according to the number of file lines and the number of bytes, and automatically add numbers to multiple output files.
Split [Option] Small file output from the large file to be cut
| Option |
Meaning |
| -N |
Used to specify the number of lines cut into small files |
| -B |
Specifies the bytes to be cut into small files. |
| -C |
Similar to-B, however, the completion of each line is maintained whenever possible during cutting. |
Split-2 input (x by default) split-b100 input split-C100 input inputtr
The current character conversion function can be completed by tr, but tr is simple
Tr [Option] string 1 string 2 <input file
| Option |
Meaning |
| -C |
Returns the character set of string 1. |
| -D |
Delete all characters in string 1 |
| -S |
Delete all recurring character sequences and retain only one |
Tar
Archive command to achieve packaging and decompression files
Tar [Option] File Name or directory name
| Option |
Meaning |
| -C |
Create a new package |
| -X |
Decompress the file |
| -T |
List Package content |
| -F |
This option is usually required to use compressed files or devices. |
| -Z |
Use gzip to compress and decompress files. If you add this option to create a compressed package, you also need to add this option during decompression. |
| -J |
Bz2 |
| -V |
View Process |
| -R |
Add a file to Baozhong |
Gzip compressed file
Linux text processing summary
| Linux text processing commands |
Application |
| Grep |
Search for regular expressions and print the rows. grep command family: grep, egrep, fgrep |
| Sed |
Stream Editing: acts as a copy of the input file in the buffer to edit the input file. |
| Awk |
It is characterized by processing structured files. The so-called structured file refers to files that are divided into domains and records. |
| Sort |
Sort text |
| Uniq |
Remove consecutive duplicate rows of text, or count the number of duplicate rows |
| Join |
Similar to database connection operations |
| Cut |
Extract text from standard input or input files by line or by field |
| Paste |
It is used to paste content from multiple files or standard output to form a new file. |
| Split |
Used to cut large files into small files |
| Tr |
Supports character replacement to filter text files. |
| Tar |
Archive commands and gzip are used to compress and decompress Linux system files. |