One Separator
1. Single separator (for example, extract the 11:22:33 string 11 22 33)
Echo 11:22:33 | awk 'in in {FS = ":" };{ Print $1 "" $2 "" $3 ;};'
2. Define multiple delimiters (for example, extract string 11 22 33 44 from string 33 & 44)
Echo '11: 22 #33 & 44' | awk' begin {FS = "[: # &]"}; {print $1 "" $2 "" $3 "" $4 ;};'
3. Define multiple separator strings (for example, extract the 11: 22 #33 & 44 string 11 22 33 44)
Echo '11: 22 #33 & 44 '| awk' begin {FS = "(::|##| &&)"}; {print $1 "" $2 "" $3 "" $4 ;};'
4. note that FS is represented by a regular expression. If there is a string 11 #22 with the separator #, it will be split into three strings, and $2 is empty, for example, if the length is not fixed
Echo '11 # 22' | awk' begin {FS = "# +" };{ Print $1 "" $2 };'
5. You may want to separate Example 3 :, #, &
Echo '11: 22 #33 & 44 '| awk' begin {FS = "(: + | # + | & + )"}; {print $1 "" $2 "" $3 "" $4 ;};'
For the second statistical problem, the following figure shows the total number of all a B c Outputs A: Total number B: Total number ....
A=1B=20C=3C=-5A=4A=3D=8D=-9xx=11xx=22
1. The join array sum [$1] and for loop are used here.
Awk 'in in {FS = "=" ;};{ sum [$1] + = $2 ;}; end {for (key in sum) {print key ": "sum [Key]} 'test
2. Problem: if there is an empty row above, do you need to skip the process before processing the empty row?
Awk 'in in {FS = "= ";};! /^ * $/{Sum [$1] + = $2;}; end {for (key in sum) {print key ":" sum [Key]} 'test
! /^ * $/Indicates that only blank rows are processed,
3. problem: if you add a line similar to d =-9 = 33, there is no problem, so you have to change it to only process two fields. If the output of other fields has an error line, skip the blank line here.
Awk 'in in {FS = "= ";};! /^ * $/{If (NF = 2) {sum [$1] + = $2;} else {print "error line" Nr ": "$0 ;}; end {for (key in sum) {print key": "sum [Key]} 'test
4. Problem: If the accumulated number $2 is not a number, should it be skipped.
Awk 'in in {FS = "= ";};! /^ * $/{If (NF = 2) {if ($2 !~ /^-* [0-9] + $/) next; sum [$1] + = $2;} else {print "error line" Nr ": "$0 ;}; end {for (key in sum) {print key": "sum [Key]} 'test
If ($2 !~ /^-* [0-9] + $/) next; indicates reading a row if the integer does not match)
5. Problem: What should I do if there are spaces before and after the accumulated number $2? So the space at the beginning and end is removed before determining whether there are digits.
Awk 'in in {FS = "= ";};! /^ * $/{If (NF = 2) {gsub ("(^ *) | (* $)", "", $2); if ($2! ~ /^-* [0-9] + $/) next; sum [$1] + = $2;} else {print "error line" Nr ": "$0 ;}; end {for (key in sum) {print key": "sum [Key]} 'test
Gsub ("(^ *) | (* $)", "", $2); Removes spaces at the beginning and end and saves them to $2; similarly, you can remove spaces at the beginning and end of Field 1.