简体   繁体   中英

add number to adjacent column and increment baed on match bash awk

I want to add a second column of data to a set of coordinates (one line each), that groups those coordinates together based on a re-occuring string or delimiter (male_position).

Here is an example dataset:

male_position
0.0
0.0
2.2
3.0
4.5
male_position
0.0
1.2
20.2
male_position
1.0
2.0

Id like to add a grouping ID to the next column:

script.awk example.file
male_position  1
0.0  1  
0.0  1
2.2  1
3.0  1
4.5  1
male_position  2
0.0  2
1.2  2
20.2  2 
male_position  3
1.0  3
2.0  3

Im not quite where to start, but think awk would get it done. I can add consecutive numbers(by line) in a column with awk '$2=(FNR FS $2)' myFile for example , but that obviously doesn't get it done in terms of grouping the coordinates based on the match/delimiter and then ticking up at each match.

Following awk may help you on same.

awk  '/male_position/{count++} {print $0,count}'  Input_file

Explanation:

/male_position/ : Searching for string male_position in a current line if condition is true then do instructions following it.

{count++} : variable named count and increment its value each time with value of 1 whenever cursor come here.

{print $0,count} : Printing the value of $0 (current line) and count value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM