2013-03-18 82 views
1

我是一個Unix shell腳本新手。我知道幾種不同的方式來找到重複。但無法找到一種簡單的方法來刪除重複項,同時保持原始順序(因爲使用排序 - 失去原來的順序)。通過Unix shell腳本查找並刪除重複的字符串。如何?

例子:腳本調用dedupe.sh

運行示例:

dedupe.sh

cat dog cat bird fish bear dog 

結果:cat dog bird fish bear

+0

這不是那種東西shell腳本是專爲。你在使用哪種外殼?你應該爲此添加一個perl標籤,有人會用perl中的解決方案來彈出。 – 2013-03-18 00:48:31

+0

這是在文件中?如果是,請使用'uniq'。 – squiguy 2013-03-18 00:50:49

回答

1

你說的Perl?

perl -e 'while([email protected]){$seen{$_}++||print}print"\n" ' \ 
cat dog cat bird fish bear dog 

等效地,dedupe.pl包含:

#!/usr/bin/perl 
while ($w = shift @ARGV) { 
    $seen{$w}++ || print "$w"; 
} 
print "\n"; 

現在chmod u+x dedupe.pl和:

./dedupe.pl cat dog cat bird fish bear dog 

無論哪種方式,輸出是任意的。

cat dog bird fish bear 
2

使用

$ printf '%s\n' cat dog cat bird fish bear dog | awk '!arr[$1]++' 
cat 
dog 
bird 
fish 
bear 

$ echo 'cat dog cat bird fish bear dog' | awk '!arr[$1]++' RS=" " 

$ printf '%s\n' cat dog cat bird fish bear dog | sort -u 

如果它工作在,它會在腳本作品=)

0

Ahh perl ...只寫語言。 :)

只要你打電話給另一種腳本語言,不妨考慮一下可讀性。 :)

#!/usr/bin/env ruby 

puts ARGV.uniq.join(' ') 

這意味着:

puts = "print whatever comes next" 
ARGV = "input argument array" 
uniq = "array method to perform the behavior you're looking for and remove duplicates" 
join(' ') = "join with spaces instead of default of newline. Not necessarily needed if you're piping to something else" 
相關問題