awk programming

1 awk processing flow
  awk reads the contents of the text file in order, and the domain is separated by spaces by default. From the first line to the last line of the text,
  you can re-specify the split field designation through the F tag.
 
  //Read the specified file line by line and split the fields with: to print out the positive line and the values ​​of the first, second, and third fields respectively
 
$ awk -F : '{print $0,$1,$2,$3}' filename

 
  //Different methods achieve the same function above
  $ awk 'BEGIN{FS=":"}{print $0,$1,$2,$3}' filename
  //The BEGIN here refers to the instruction before the operation of the specific function, usually Used with END, you can also use
 
2 awk alone to check whether the string contains a substring
 
$ awk '{if($0 ~"root"){print "it matched !"} else{print "nothing..."}}'

 
  ~ is a regular match that includes substrings. You can also use !~ not to include. Similarly, you can also use >,>=,<,<=,==,!= for calculation and comparison.
 
  The '//' tag can also be used to include substrings. E.g
 
$ awk '/root/' /etc/passwd

  The above command will print out a whole line of information including the root substring.
 
  Similarly, you can also use the '//' tag to intercept a whole piece of information in the text
 
$ awk '/this is begin str/,/this is end str/' filename

  The above command will print out the text information from the beginning to the end of the text file.
 
  awk queries the string starting with a specific character
 
$ awk '$0 ~/^Akl.*/{print $0}' filename

  The above command completes the query of the data line starting with Akl in the specified file.
 
3 The processing of the awk function is
  more general. The processing command can be written in a specific file, and calling it in an appropriate place can increase the reusability of the code.
  For example:
  define a The function body is in the file fuc.awk, its content is edited to {print $1, $2 * $3}
  to call this function 
$ awk -f fuc.awk filename

 
4 awk use loops
  You can use for loops in awk, or you can use while loops
  for examples:
 
$ echo "" | awk '{for(i=1;i<5;i++){print i}}'

  The above command will output 1,2,3,4
 
  while instance:
 
$ echo "" | awk 'BEGIN{uk=10;print "this is begin line"}{while(uk > 0){print uk;uk--}}END{print "this is end line"}'

 
5 The use of awk NF NR
  NF : Number of Field, returns a value, indicating the number of specified fields
  $NF: returns the value of the field itself
 
  NR: Number of Records, returns a value, indicating that it has been read How many rows of data were fetched.
 

 
 
 

Guess you like

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