The awk field of Linux learning

awkThe content of each line is called 记录, and the string separated by special characters is called 字段.

field reference

echo 'a : 1 : good ::::' >> awktest.txt
echo 'b : 2 : well ::::' >> awktest.txt
echo 'c : 3 : food ::::' >> awktest.txt
echo 'd : 4 : hood ::::' >> awktest.txt
echo 'e : 5 : bell ::::' >> awktest.txt
echo 'o : 6 : toll ::::' >> awktest.txt
echo '1 : a : good : h :::' >> awktest.txt
echo '2 : b : well : say :::' >> awktest.txt
echo '3 : c : food : gold :::' >> awktest.txt

Put the following content:

a : 1 : good ::::
b : 2 : well ::::
c : 3 : food ::::
d : 4 : hood ::::
e : 5 : bell ::::
o : 6 : toll ::::
1 : a : good : h :::
2 : b : well : say :::
3 : c : food : gold :::

write into awktest.txtit.
insert image description here

awkBy default, spaces are used as field separators (column separators) for field separation. Field separation refers to splitting records into fields. awk '{ print $6}' awktest.txtwill output the sixth field of each line to the screen.
insert image description here

Well enough

awk 'pattern { action }
pattern { action }
pattern { action }' file

Action output.

awk '/^a/{ print $6}
/^3/{print $7}' awktest.txt

You can first output athe sixth field in the record starting with , and then output 3the seventh field in the record starting with , and use regular expressions here.
insert image description here

Options can be used -Fto modify the field separator. [[:space:]]is a space, awk -F "[[:space:]]:[[:space:]]" '{ print $2}' awktest.txtyou can use 空格+ :+ 空格as the field separator, and then output the second field in each record.
insert image description here
You can also use variables to record the line number, awk -F "[[:space:]]:[[:space:]]" '{ print x++,$3}' awktest.txtyou can use 空格+ :+ 空格as the field separator, and then output the third field in each record, and write the line number minus 1 in front.
insert image description here

This article is a study note for Day 8 in August, and the content comes from Geek Time "100 Lectures on Linux Practical Skills" .

Guess you like

Origin blog.csdn.net/qq_42108074/article/details/132178418