Tom*_*ley 6 linux text-processing
我想从文件中删除重复的行,但在文件中留下 1 次。
文件示例:
this is a string
test line
test line 2
this is a string
Run Code Online (Sandbox Code Playgroud)
从上面的例子中,我想删除 1 个“这是一个字符串”。
最好的方法来做到这一点?
stuff.txt包含:one
two
three
one
two
four
five
Run Code Online (Sandbox Code Playgroud)
假设您不介意行已排序,则从文件中删除重复的行
$ sort -u stuff.txt
five
four
one
three
two
Run Code Online (Sandbox Code Playgroud)
说明:发送到 sort 的 u 标志表示对文件的行进行排序并强制唯一。
从文件中删除重复的行,保留原始顺序,保留第一个:
$ cat -n stuff.txt | sort -uk2 | sort -nk1 | cut -f2-
one
two
three
four
five
Run Code Online (Sandbox Code Playgroud)
说明:传递给 cat 的 n 标志将行号附加到每行的左侧,加上空格,然后第一个排序表示按唯一性排序,但仅在第一个单词之后,第二个排序命令表示使用我们在步骤 1 中存储的行号再按原来的顺序再打,终于把第一个字剪掉了。
从文件中删除重复的行,保留顺序,保持最后。
tac stuff.txt > stuff2.txt; cat -n stuff2.txt | sort -uk2 | sort -nk1 | cut -f2- > stuff3.txt; tac stuff3.txt > stuff4.txt; cat stuff4.txt
three
one
two
four
five
Run Code Online (Sandbox Code Playgroud)
说明: 和之前一样,但是 tac 反转文件,达到预期的结果。
小智 5
由于删除除最后一个出现之外的所有内容与删除除第一个以外的所有内容相反,因此还有以下解决方案:
tac file | awk '! seen[$0]++' | tac
Run Code Online (Sandbox Code Playgroud)
tac反转文件中的行,并且awk仅输出第一次出现的重复行。
这留下了第一个出现的情况:
awk '! a[$0]++' inputfile
start cmd:> echo 'this is a string
cont. cmd:> test line
cont. cmd:> test line 2
cont. cmd:> this is a string' | awk '! a[$0]++'
this is a string
test line
test line 2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18197 次 |
| 最近记录: |