当前位置:网站首页>Awk example skills

Awk example skills

2022-04-23 20:43:00 baboon_ chen

One 、 Transpose files


hypothesis file.txt The contents of the document are as follows :

name age
alice 21
ryan 30


It should output :

name alice ryan
age 21 30


convert.awk

##
## awk -f convert.awk file.txt

{
     # The code in this brace is   Processing of text 
    # NF A number of columns ,NR Indicates the number of lines read 
    #  Be careful for Medium i from 1 Start ,i There is no type before 
    for (i=1; i<=NF; i++){
    # For each column 
        if(NR==1){
           # If it's the first line 
            # Will be the first i The value of the column is stored in res[i],$i It means the first one i The value of the column ,i Is the subscript of the array , Take the column serial number as the subscript ,
            # Arrays can be used directly without definition 
            res[i]=$i;   
        }
        else{
    
            # Not the first line , Map this line to i The values of the columns are spliced into res[i]
            res[i]=res[i] " " $i
        }
    }
}
# BEGIN{}  What to do before scanning a file ;END{}  What to do after file scanning .
END{
    
    # The output array 
	for (i=1; i<=NF; i++){
    
		print res[i]
	}
}

版权声明
本文为[baboon_ chen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210546351155.html

随机推荐