(6) or modify the field induced NF recalculated $ 0

Linkage effects modify the field values ​​or NF

Note that the following is calculated and divided two words: segmentation indication FS (field Separator), calculates a variable using the predefined OFS (Output Field Separator).

  1. Modification $0, will be used FSto re-split field, it will affect$1、$2...
  2. Modification $1、$2, according $1to the $NFre-calculation of the fields$0
    • Even $1 = $1so constant modification of the original value, the same will be recalculated$0
  3. Assignment for the field does not exist, add fields and used as needed to fill the empty string in the middle of the field, and used OFSto recalculate$0
    • awk 'BEGIN{OFS="-"}{$(NF+2)=5;print $0}' a.txt
  4. Increase the value of NF, will add an empty string field and use OFSrecalculate$0
    • awk 'BEGIN{OFS="-"}{NF+=3;print $0}' a.txt
  5. NF reduced value, a certain number of discarded tail field, and used OFSto recalculate$0
    • awk 'BEGIN{OFS="-"}{NF-=3;print $0}' a.txt

About $ 0

When reading a record, to be stored exactly to $0them.

awk '{print $0}' a.txt

But as long as there has been any kind of operation leads to the above mentioned $ 0 recalculated, OFS will be used immediately to rebuild $ 0

In other words, it did not lead to $0reconstruction, $0it has been exactly the data, specify the OFS also invalid.

awk  ' the BEGIN {the OFS = "-"} {0} Print $ ' a.txt # invalid here the OFS

When $0the reconstruction, the reconstruction will automatically use the OFS, OFS even if not specified, it will default value (space) for reconstruction.

[@ docker- the root 01 ~] # awk  ' {+ = $ 10. 4; the OFS = "-"; Print $ 0} ' a.txt 
# inactive for the first row the OFS 
[@ Docker the root - 01 ~] # awk  ' {$. 4 = 10 +; the OFS = "-"; $ = $. 1. 1; Print $ 0} ' a.txt 
# is valid for all rows

Focus on $0reconstruction is a very useful skill.

For example, by the following reconstruction $0to achieve the removal of line trailing spaces and compression techniques middle space:

[root@docker-01 ~]# echo "   a  b  c   d   " | awk '{$1=$1;print}'
a b c d
[root@docker-01 ~]# echo "     a   b  c   d   " | awk '{$1=$1;print}' OFS="-"  
a-b-c-d

 

Guess you like

Origin www.cnblogs.com/liujunjun/p/12389767.html