1

For example, this is the list.txt

Joe 3
Jack 1
Ulysses 6
Fox 2
Cassidy 1
Jones 6
Kevin 7

Then the output should be 5 because there are 5 different values in the 2rd column.

How should I finish this by only using sort cut wc uniq?

I have an idea, first use sort -k2n to sort the second column in increasing order and then use uniq to eliminate the second-column duplicated rows, and then the result would be like

Cassidy 1
Fox 2
Joe 3
Jones 6
Kevin 7

and then I use cut -d ' ' -f2 to list all the numbers like 1 2 3 6 7 and then I use wc -d to count the number of distinct values and this will return 5.

What should I do in the uniq part to eliminate the duplicated rows with the same number?

Is there a simple way to accomplish this?

  • This is the second week of learning Unix. Do you think that my method is way too long and stupid? – Ulysses Jan 31 '18 at 20:03
1

I would start with cut since you only care about uniqueness in column 2:

cut -d' ' list.txt

results in:

1
2
1
3
6
7
6

Now you want unique values; uniq will do that, but only if it's sorted. If you're going to sort, go ahead and use sort's -u flag:

cut -d' ' -f2 list.txt | sort -u

Results in:

1
2
3
6
7

and now you can use wc to count the number of lines of output:

cut -d' ' -f2 list.txt | sort -u  | wc -l

which gives you:

5

Note that we're relying a specific format for the list.txt file -- no spaces in people's names!

  • It is traditional here to think with a ✓(click the tick) – ctrl-alt-delor Jan 31 '18 at 23:24
1

I would go with:

sort -k2,2 -u names | wc -l
5

Where names has this content:

cat names
Joe 3
Jack 1
Ulysses 6
Fox 2
Cassidy 1
Jones 6
Kevin 7
  • Clever combination of the key field with -unique! – Jeff Schaller Jan 31 '18 at 20:15
0

Since you are required to use -sort -cut -wc -uniq, then it seems that the required command line should be something like this:

$ cut -d' ' -f2 file.txt | sort -n | uniq | wc -l
5

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.