0

Below I have given my file (filename = 1.txt) structure. I want to count the number frequency from the first column and it should be started from line 3. Because the first line contains 411 and second line contain some text which is not the interest of mine.

I can count a specific number using below:

awk '($1==15){ ++count } END{ print count }' 1.txt> output.txt

my file structure:

411
Lattice="156.0 0.0 0.0 0.0 156.0 0.0 0.0 0.0 156.0" 
1 410.0 2 1
2 1059.0 2 2
2 1060.0 2 3
3 2117.0 2 4
4 4726.0 2 5
5 3219.0 2 6
6 4744.0 2 7
7 4918.0 2 8
8 10686.0 2 9
9 11055.0 2 10
10 16475.0 2 11
11 14698.0 2 12
11 17430.0 2 13
12 15235.0 2 14
13 15799.0 2 15
14 21476.0 2 16
15 18561.0 2 17
15 18562.0 2 18
15 21595.0 2 19
15 21636.0 2 20
15 21684.0 2 21
16 24262.0 2 22
14 21475.0 2 23
17 24674.0 2 24

my desired output

 1 1
 2 2
 3 1
 4 1
 .
 .
14 2
15 5

2 Answers 2

4

You can use an associative array that is keyed on the column value, assigning values only from the third record (line) onward (NR>2):

$ awk 'NR>2 {count[$1]++} END {for (i in count) print i, count[i]}' 1.txt
1 1
2 2
3 1
4 1
5 1
6 1
7 1
8 1
9 1
10 1
11 2
12 1
13 1
14 2
15 5
16 1
17 1

Note that the order of array traversal is not guaranteed - you may need additional sorting if output order is important.

1
  • Dear Sir, thank you very much. it is working.
    – Alex
    Jul 14, 2019 at 4:00
1

Tried with below script and it worked fine

for i in `awk 'NR >2 {print $1}' p.txt| sort -k1 -n -u`; do  echo $i; awk 'NR >2 {print $1}' p.txt|awk -v i="$i" '$1 == i {print $1}'| awk '{print NR}'| sed -n '$p'; done| sed "N;s/\n/ /g"

output

1 1
2 2
3 1
4 1
5 1
6 1
7 1
8 1
9 1
10 1
11 2
12 1
13 1
14 2
15 5
16 1
17 1
1
  • this is also working fine and output is excellent
    – Alex
    Jul 15, 2019 at 18:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.