Reputation: 5044
I have another question
I have this dataset
1955|1;.;.;.;.;.;.;
1955|1;.;.;.;.;.;.;
1955|1;.;.;.;.;.;.;
1955|2;.;.;.;.;.;.;
1955|2;.;.;.;.;.;.;
1955|2;.;.;.;.;.;.;
1955|3;.;.;.;.;.;.;
1955|3;.;.;.;.;.;.;
1955|3;.;.;.;.;.;.;
1955|4;.;.;.;.;.;.;
1955|4;.;.;.;.;.;.;
1955|4;.;.;.;.;.;.;
1956|1;.;.;.;.;.;.;
1956|1;.;.;.;.;.;.;
Below is the result I want:
1955|1;.;.;.;.;.;.;
1955|2;.;.;.;.;.;.;
1955|3;.;.;.;.;.;.;
1955|4;.;.;.;.;.;.;
1955|5;.;.;.;.;.;.;
1955|6;.;.;.;.;.;.;
1955|7;.;.;.;.;.;.;
1955|8;.;.;.;.;.;.;
1955|9;.;.;.;.;.;.;
1955|10;.;.;.;.;.;.;
1955|11;.;.;.;.;.;.;
1955|12;.;.;.;.;.;.;
1956|1;.;.;.;.;.;.;
1956|2;.;.;.;.;.;.;
I'm using this snippet of code
for file in /cygdrive/c/work/studies/project/data/trim/"$datenow"/*v3.tsv;
do
awk -F\| '$1!=l{c=$2}{$2=c++}{l=$1}1' OFS=\| "${file}" > "${file%.*}v4.${file##*.}"
done`
However, it is not working the way I'm expecting as it only gives me this
1955|1
1955|2
1955|3
1955|4
1955|5
1955|6
1955|7
1955|8
1955|9
1955|10
1955|11
1955|12
1956|1
1956|2
What am I doing wrong?
Edited: I've tried all the possible variations but it is not giving me the results I'm expecting, with -F\|
and OFS=\;
or -F\;
and OFS=\|
but to no avail
Upvotes: 0
Views: 139
Reputation: 203615
$ awk 'BEGIN{FS=OFS="|"} $1!=prev{c=0} {sub(/^[^;]+/,++c,$2); prev=$1} 1' file
1955|1;.;.;.;.;.;.;
1955|2;.;.;.;.;.;.;
1955|3;.;.;.;.;.;.;
1955|4;.;.;.;.;.;.;
1955|5;.;.;.;.;.;.;
1955|6;.;.;.;.;.;.;
1955|7;.;.;.;.;.;.;
1955|8;.;.;.;.;.;.;
1955|9;.;.;.;.;.;.;
1955|10;.;.;.;.;.;.;
1955|11;.;.;.;.;.;.;
1955|12;.;.;.;.;.;.;
1956|1;.;.;.;.;.;.;
1956|2;.;.;.;.;.;.;
Upvotes: 1
Reputation: 13
A very similar, but equally effective answer:
awk -F"[;|]" 'OFS=";" {$2=a[$1]+++1;sub(/;/,"|"); print}' file
Explanation
Define two possible field separators ; and |
-F"[;|]"
Define a single output field separator ;
OFS=";"
Replace the content of the second field (after the pipe) with an array indexed by the first field that increments with each occurrence
awk -F"[;|]" 'OFS=";" {$2=a[$1]+++1
substitute the first FS ; with |
and print
Upvotes: 0
Reputation: 41456
You can try this awk
awk -F"[;|]" '{$2=c++%12+1;sub(/;/,"|")}1' OFS=\; file
1955|1;.;.;.;.;.;.;
1955|2;.;.;.;.;.;.;
1955|3;.;.;.;.;.;.;
1955|4;.;.;.;.;.;.;
1955|5;.;.;.;.;.;.;
1955|6;.;.;.;.;.;.;
1955|7;.;.;.;.;.;.;
1955|8;.;.;.;.;.;.;
1955|9;.;.;.;.;.;.;
1955|10;.;.;.;.;.;.;
1955|11;.;.;.;.;.;.;
1955|12;.;.;.;.;.;.;
1956|1;.;.;.;.;.;.;
1956|2;.;.;.;.;.;.;
This version does not change any formatting.
awk '{sub(/\|[0-9]+/,"|"c++%12+1)}1' file
1955|1;.;.;.;.;.;.;
1955|2;.;.;.;.;.;.;
1955|3;.;.;.;.;.;.;
1955|4;.;.;.;.;.;.;
1955|5;.;.;.;.;.;.;
1955|6;.;.;.;.;.;.;
1955|7;.;.;.;.;.;.;
1955|8;.;.;.;.;.;.;
1955|9;.;.;.;.;.;.;
1955|10;.;.;.;.;.;.;
1955|11;.;.;.;.;.;.;
1955|12;.;.;.;.;.;.;
1956|1;.;.;.;.;.;.;
1956|2;.;.;.;.;.;.;
It just replace the number after |
Upvotes: 1