DK *_*ose 12 command-line sort
我的参考文献是一个文本文件,其中包含一长串条目,每个条目都有两个(或更多)字段。
第一列是引用的 url;第二列是标题,根据条目的制作方式可能会有所不同。可能存在或可能不存在的第三个字段相同。
我想识别但不删除第一个字段(引用 url)相同的条目。我知道,sort -k1,1 -u
但这会自动(非交互地)删除除第一次命中之外的所有内容。有没有办法让我知道这样我可以选择保留哪个?
在具有相同第一个字段 ( http://unix.stackexchange.com/questions/49569/
) 的三行的以下摘录中,我想保留第 2 行,因为它有附加标签(排序、CLI)并删除第 1 行和第 3 行:
http://unix.stackexchange.com/questions/49569/ unique-lines-based-on-the-first-field
http://unix.stackexchange.com/questions/49569/ Unique lines based on the first field sort, CLI
http://unix.stackexchange.com/questions/49569/ Unique lines based on the first field
Run Code Online (Sandbox Code Playgroud)
是否有程序可以帮助识别此类“重复项”?那么,我可以通过亲自删除第 1 行和第 3 行来手动清理吗?
Lek*_*eyn 11
这是一个可以用uniq
命令解决的经典问题。uniq
可以检测重复的连续行并删除重复项 ( -u
, --unique
) 或仅保留重复项 ( -d
, --repeated
)。
由于重复行的排序对您来说并不重要,因此您应该先对其进行排序。然后使用uniq
仅打印唯一行:
sort yourfile.txt | uniq -u
Run Code Online (Sandbox Code Playgroud)
还有一个-c
( --count
) 选项,用于打印选项的重复数量-d
。有关uniq
详细信息,请参阅 的手册页。
如果您真的不关心第一个字段之后的部分,则可以使用以下命令查找重复键并为其打印每个行号(附加另一个| sort -n
以按行排序输出):
cut -d ' ' -f1 .bash_history | nl | sort -k2 | uniq -s8 -D
Run Code Online (Sandbox Code Playgroud)
由于您想查看重复的行(使用第一个字段作为键),因此不能直接使用uniq
. 使自动化变得困难的问题是标题部分各不相同,但程序无法自动确定应将哪个标题视为最终标题。
这是一个 AWK 脚本(将其保存到script.awk
),它将您的文本文件作为输入并打印所有重复的行,以便您可以决定要删除哪些行。( awk -f script.awk yourfile.txt
)
#!/usr/bin/awk -f
{
# Store the line ($0) grouped per URL ($1) with line number (NR) as key
lines[$1][NR] = $0;
}
END {
for (url in lines) {
# find lines that have the URL occur multiple times
if (length(lines[url]) > 1) {
for (lineno in lines[url]) {
# Print duplicate line for decision purposes
print lines[url][lineno];
# Alternative: print line number and line
#print lineno, lines[url][lineno];
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果我理解你的问题,我认为你需要这样的东西:
for dup in $(sort -k1,1 -u file.txt | cut -d' ' -f1); do grep -n -- "$dup" file.txt; done
Run Code Online (Sandbox Code Playgroud)
或者:
for dup in $(cut -d " " -f1 file.txt | uniq -d); do grep -n -- "$dup" file.txt; done
Run Code Online (Sandbox Code Playgroud)
file.txt
包含您感兴趣的数据的文件在哪里。
在输出中,您将看到两次或多次找到第一个字段的行数和行数。