1. awk
Assuming an existing file test1
with the following contents:
name=xiaoming
passwd=123456
To extract the username and password from it:
# 提取用户名
cat test1 | grep 'name' | awk -F '=' '{print $2}'
# 提取密码
cat test1 | grep 'passwd' | awk -F '=' '{print $2}'
cat test1 | awk -F '=' '{print $2}'
xiaoming
123456
awk -F '=' '{print $2}' test1
xiaoming
123456
Other explanations:
The options of the awk command -F
indicate which symbols are used to split, $n
indicating the first n
parameter (the nth parameter after the split)
Two terms in awk:
A record (by default, each line of text)
fields (by default, a string delimited by spaces or TABs in each record)
$0
represents a record, $1
representing the first field in the record.
Generally print $0
, it is to print the entire line content ( $0
no backslash is required in front), which print $1
means that only the first field of each line is printed.
$ cat test2.txt
i am a girl
you are a boy
it is a bear
$ sed -n '2p' test2.txt | cut -d ' ' -f4
boy
$ head -n 2 test2.txt |cut -d ' ' -f4
girl
boy
$ head -n 2 test2.txt | tail -n 1 | cut -d ' ' -f4
boy
$ awk '{print $1,$4}' test2.txt
i girl
you boy
it bear
$ awk -F ' ' '{print $4}' test2.txt
girl
boy
bear
$ awk -F ' ' 'NR==2{print $4}' test2.txt
boy
$ awk '{print NR}' test2.txt | tail -n1
3
$ awk '{print NR}' test2.txt
1
2
3
$ awk 'END{print NR}' test2.txt
3
2. cut
The Linux cut command is used to display the text num1 to num2 from the beginning of each line.
-d : Custom delimiter, default is tab.
-f : Used with -d, specifies which region to display.
example
$ cat test2.txt
i am a girl
you are a boy
it is a bear
$ cat test2.txt | cut -d ' ' -f4
girl
boy
bear