【问题标题】:How can I delete n-times-duplicate lines in a file in Linux shell?如何在 Linux shell 中删除文件中的 n 次重复行?
【发布时间】:2023-03-23 03:34:01
【问题描述】:

我有几句话:

one
two
two
three

我有一个文件,其中每个单词都重复了 n 次。例如,在 n=2 时,给定文件是:

one
two
two
three
two
three
two
one

问题是如何恢复原来的一组词(我知道$n这个数字)。

注意“二”这个词应该出现两次,所以sort -u file.txtsort file.txt | uniq 在这里不是答案!

【问题讨论】:

  • 所以只有two 应该在输出中出现两次?
  • 是的,答案是四个字(一二二三)任意顺序
  • 以下答案对您没有帮助吗?

标签: linux shell uniq


【解决方案1】:

此行为您提供未排序原始行:

awk -v n="2" '{a[$0]++}END{for(x in a)for(i=1;i<=a[x]/n;i++)print x}' file

n 可以是可变的,我使用了硬编码的2。使用您当前的输入文件,它会输出:

two
two
three
one

输出未排序,因为只有输入文件无法知道“原始”文件的顺序。

用其他例子测试:

#still n=2
kent$  cat f  
one
one
one
one
three
three
two
two
two
two
two
two

kent$  awk -v n="2" '{a[$0]++}END{for(x in a)for(i=1;i<=a[x]/n;i++)print x}' f
three
two
two
two
one
one

#now n=4:

kent$  cat f
one
one
one
one
one
one
one
one
three
three
three
three
two
two
two
two
two
two
two
two
two
two
two
two

kent$  awk -v n="4" '{a[$0]++}END{for(x in a)for(i=1;i<=a[x]/n;i++)print x}' f
three
two
two
two
one
one

【讨论】:

  • +1 为这个不太明确的问题提供了很好的 awk 命令。
  • 我会给 -1 以鼓励用户发布令人费解和难以理解的“问题”,但这对任何人都没有任何好处。 +1 努力
  • 最初,问题在于解析用于将 MPI 作业提交到集群的 PBS_NODEFILE 与 PBS 作业调度程序...
【解决方案2】:

还有一个:

n=2
inp="./in"

while read -r cnt word
do
        seq -f "$word" $(( cnt / n ))
done < <(sort "$inp" | uniq -c)

打印

one
three
two
two

perl 变体

perl -nE '$s{$_}++}{print "$_"x($s{$_}/2) for keys %s' < in

最后, bash (4+)

file="./in"
div=2

declare -A w
while read -r word
do
    [[ -z "${w[$word]}" ]] && order+=($word)
    let w[$word]++
done < "$file"
for word in "${order[@]}"
do
    cnt=$(( ${w[$word]} / div ))
    for(( i=0; i < $cnt ; i++ ))
    do
        echo $word
    done
done

按照第一个在输入中找到单词的顺序打印,例如:

one
two
two
three

【讨论】:

    猜你喜欢
    • 2016-12-07
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    • 1970-01-01
    • 2012-04-05
    • 2020-01-27
    • 2013-03-02
    相关资源
    最近更新 更多