AWK
The difference between AWK and sed
- AWK is used for more standardized text processing, used to count the number and output the specified field
- sed is used to process non-standard text into more standardized text
AWK field reference and separation
- AWK is also read by line. Each line is called a record. Words separated by spaces and tabs are called fields. You can specify the separator to separate fields.
- Use $ 1 $ 2 ... $ n for each field, and $ 0 for an entire line
- awk '{print $1,$2,$3}' filename
- awk -F "'"' / ^ menu / {print $ 2} '/boot/grub2/grub.cfg to split the field with a', remove the kernel information in the file
- {print x ++, $ 2} x ++ can display the number of lines
- -F option is used to specify the separator
- awk -F ',' '{print $1,$2,$3}' filename
- Delimiters can be expressed using regular expressions
AWK expression
- System variables
-
FS and OFS field separators, OFS indicates the output field separators
- head -5 / etc / passwd | awk 'BEGIN {FS = ":"} {print $ 1}'
BEGING, pre-process before reading the file. Before reading the passwd file, specify the ":" as the delimiter through the FS option. - head -5 / etc / passwd | awk 'BEGIN {FS = ":"; OFS = "-"} {print $ 1, $ 2}' OFS = "-", OFS is after finding the field, the system uses spaces by default Separation, and OFS changed the default separation symbol.
- head -5 / etc / passwd | awk 'BEGIN {FS = ":"} {print $ 1}'
-
RS line record separator, record line, RS is a newline by default, when multiple lines are combined into a single line, use RS to process
- head -5 / etc / passwd | awk 'BEGIN {RS = ":"} {print $ 1}' The system default line record separator is a line break, RS = ":", replace the line record separator with:
-
NR and FNR rows
- head -5 / etc / passwd | awk '{print NR, $ 0}' NR shows the line number, $ 0 shows the line content
- awk '{ print NR,$0 }' /etc/hosts /etc/hosts
- awk '{print FNR, $ 0}' / etc / hosts / etc / hosts
For single files, there is no difference between using NR and FNR. If you connect multiple files, NR will always sort the content in order, without distinguishing files; FNR is based on Sort the files first, and then sort them individually.
-
The number of NF fields, the content of the last field can be taken out with $ NF
- head -5 / etc / passwd | awk 'BEGIN {FS = ":"} {print NF}' outputs how many fields are in each line
-