awk extension

  1. Using external shell variables in awk http://ask.apelearn.com/question/199

Test file awk.txt

及格:张三:67            
不及格:李四:58            
及格:小明:72            
优秀:小虎:95            
不及格:小兰:49
编写脚本awk1.sh:
#!/bin/bash
sort -n awk.txt|awk -F ":" '{print $1}'|uniq >考试.txt
sort awk.txt|awk -F ":" '{print $1}'|uniq -c >123.txt
for a in `cat 考试.txt`;do
        echo "[$a]":`awk -v c=$a   '$2==c {print $1}' 123.txt`人
        awk -v b=$a -F ":" '{OFS=":"} $1==b {print $2,$3}' awk.txt
done
[root@linux-128 test]# sh awk1.sh
[不及格]:2人
李四:58
小兰:49
[及格]:2人
张三:67
小明:72
[优秀]:1人
小虎:95
  • Note: The -v option is used to define parameters, here it means assigning the value of variable a to b
  • As many variables need to be assigned, as many -v options are required. Applied to the script:
  1. Awk merges a file  http://ask.apelearn.com/question/493  I have such a requirement, I need to merge the same lines in the first column of two files into the same line. For example, there are two files with the following contents
[root@linux-128 awk]#cat 1.txt    
1 aa
2 bb
3 ee
4 ss

[root@linux-128 awk]#cat 2.txt
1 ab
2 cd
3 ad
4 bd
5 de
[root@linux-128 awk]# awk 'NR==FNR{a[$1]=$2}NR>FNR{print $0,a[$1]}'  1.txt  2.txt
1 ab aa
2 cd bb
3 ad ee
4 bd ss
5 de
  • Explanation: NR represents the number of lines read, and FNR represents the current number of lines read, so in fact, NR==FNR means when 2.txt is read. Similarly, NR>FNR means that when reading 1.txt, the array a is actually equivalent to a map
  1. Concatenate multiple lines of a file into one  http://ask.apelearn.com/question/266  Example:
[root@linux-128 awk]#cat 2.txt
1 ab
2 cd
3 ad
4 bd
5 de

Difference between print and printf

[root@linux-128 awk]# awk '{print $1}' 2.txt
1
2
3
4
5
[root@linux-128 awk]# awk '{printf $1}' 2.txt
12345[root@linux-128 awk]# ^C

The effect of echo "" is a newline

[root@linux-128 awk]# awk '{printf $1}' 2.txt; echo""
12345

print keeps the original format printing, printf cancels all format printing, you can define the format to print.

[root@linux-128 awk]# awk '{printf ("%s+",$1)}' 2.txt;echo ""
1+2+3+4+5+

We can use sed to achieve this requirement

[root@linux-128 awk]# cat 2.txt|awk '{print $1}'|xargs|sed -r 's/ /+/'g
1+2+3+4+5
  1. The use of gsub function in awk  http://ask.apelearn.com/question/200

The use of gsub function in awk

The replacement function in gsub and sed is similar

  1. use gsub
[root@linux-128 awk]# cat 1.txt
1 aa
2 bb
3 ee
4 ss
[root@linux-128 awk]# awk 'gsub(/[0-9]/,"abc")' 1.txt
abc aa
abc bb
abc ee
abc ss
  1. Use sed to replace
[root@linux-128 awk]# sed 's/[0-9]/abc/g' 1.txt
abc aa
abc bb
abc ee
abc ss
  1. awk 'gsub(/[0-9]/,"abc",$1) {print $0}' 1.txt // replace the number in $1 with abc
[root@linux-128 awk]# awk  'gsub(/[0-9]/,"abc",$1) {print $0}' 1.txt
abc aa
abc bb
abc ee
abc ss

Guess you like

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