awk & cut

1. awk

Assuming an existing file test1with 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 -Findicate which symbols are used to split, $nindicating the first nparameter (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)
$0represents a record, $1representing the first field in the record.
Generally print $0, it is to print the entire line content ( $0no backslash is required in front), which print $1means 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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325434141&siteId=291194637
cut
awk