Extract only the first field from services.csv.
Remove duplicates and print the names in alphabetical order: api, db, web.
api,west,7
web,east,3
api,west,7
db,east,4
web,east,3
api,east,2Which command is appropriate?
uniq removes adjacent duplicate lines, so sort must place identical service names next to each other first. sort -u is a shorter alternative.
Detailed explanation
cut -d, -f1 services.csv | sort | uniqCorrect. It extracts field 1, sorts the names, and then removes adjacent duplicates.
Correct. It extracts field 1, sorts the names, and then removes adjacent duplicates.
sort services.csv | cut -d, -f1Incorrect. It sorts whole CSV lines and extracts field 1, but never removes duplicates.
Incorrect. It sorts whole CSV lines and extracts field 1, but never removes duplicates.
cut -d, -f1 services.csv | uniq | sortIncorrect. uniq only removes adjacent duplicates; repeated names that are separated in the input remain.
Incorrect. uniq only removes adjacent duplicates; repeated names that are separated in the input remain.
cut -d, -f2 services.csv | sort -uIncorrect. It extracts field 2, producing east and west rather than service names.
Incorrect. It extracts field 2, producing east and west rather than service names.
Try it yourself
An example you can run in a temporary verification environment.
cut -d, -f1 services.csv | sort | uniq
# 短い別解
cut -d, -f1 services.csv | sort -uExpected result
api
db
webKey points
- cut delimiters and field selection
- Why sort is needed before uniq
- The sort -u shorthand
Notes
- Environment:
- Command output formatting can vary slightly by distribution or tool version.
- Run the example in a temporary directory or process when possible.
Foundation review
Read the scope first
Check whether the command acts on the current shell, a new process, an existing process, or a file.
Verify the observable result
Use the supplied command and compare the output with the expected result.