Sorting and columns
Linux & the command line Lesson 10 2:20 English narration · English + 中文 subtitles burned in
Chapters
Transcript
Sort arranges lines in alphabetical order.
sort 把行按字母顺序排列。
Three fruits go in unordered and come back apple, fig, pear.
三个水果乱序进去,回来是 apple、fig、pear。
Dash r turns it round and gives you the reverse.
-r 把它反过来,给你倒序。
Sort does not change the file — it reads it and prints an ordered copy, which is why it drops straight into a pipe.
sort 不会改动那个文件——它读它,然后打印一份排好序的副本, 这也是为什么它能直接接进管道。
Now something that looks like a bug and is not.
现在说一件看起来像 bug 但其实不是的事。
Sort a list of numbers and it puts a hundred first, ahead of nine.
对一列数字排序,它会把 100 放在前面,排在 9 之前。
That is because plain sort compares them as text, character by character, and the character one comes before the character nine.
那是因为普通的 sort 是把它们当文本、一个字符一个字符比的, 而字符 '1' 排在字符 '9' 前面。
Add dash n and it reads them as numbers, and nine, twenty-five, one hundred come out in the order you expected.
加上 -n,它就把它们当数字读, 于是 9、25、100 按你期待的顺序出来。
Uniq removes repeated lines that are next to each other — which is why it almost always follows a sort.
uniq 移除彼此相邻的重复行—— 这也是为什么它几乎总是跟在 sort 后面。
Two apples become one: only one apple survives.
两个 apple 变成一个:只有一个 apple 活下来。
And dash c keeps a count in front of each line, which is how you answer "how many of each?" in a single command.
而 -c 会在每一行前面保留一个计数, 这就是用一条命令回答"每样各有多少"的方法。
Many files have columns, separated by a character — a comma, a colon, a tab.
很多文件是有列的,用某个字符隔开——逗号、冒号、制表符。
Cut pulls one out, but it has to be told two things, because a line of text does not look like a table to it.
cut 把其中一列取出来,但你必须告诉它两件事, 因为一行文本在它看来根本不像一张表。
Dash d is the delimiter — here, a colon.
-d 是分隔符——这里是冒号。
And dash f is which field you want.
而 -f 是你要第几个字段。
Field one gives the names; field two gives the ages.
第一个字段给出名字;第二个字段给出年龄。
Put the three in a pipe and you can answer a question no single one of them could.
把这三个接进一条管道,你就能回答一个它们单独谁也回答不了的问题。
How many people of each age?
每个年龄各有多少人?
Cut the age out of every line, sort the ages so equal ones sit together, then count the runs.
从每一行里把年龄剪出来,把年龄排序好让相同的挨在一起,然后数这些连续段。
Three small tools, one real answer.
三个小工具,一个真实的答案。
Four things to take with you.
带走四点。
One: sort orders lines alphabetically.
第一:sort 把行按字母顺序排列。
Two: sort dash n is needed for numbers, or a hundred comes before 9.
第二:数字要用 sort -n,否则 100 会排在 9 前面。
Three: uniq drops neighbouring repeats and dash c counts them.
第三:uniq 丢掉相邻的重复,-c 顺便计数。
Four: cut dash d sets the separator and dash f picks the field.
第四:cut 的 -d 指定分隔符,-f 挑选字段。
Now type the tasks into the terminal below.
现在把下面那些题目敲进终端里。