我是一個Unix shell腳本新手。我知道幾種不同的方式來找到重複。但無法找到一種簡單的方法來刪除重複項,同時保持原始順序(因爲使用排序 - 失去原來的順序)。通過Unix shell腳本查找並刪除重複的字符串。如何?
例子:腳本調用dedupe.sh
運行示例:
dedupe.sh
cat dog cat bird fish bear dog
結果:cat dog bird fish bear
我是一個Unix shell腳本新手。我知道幾種不同的方式來找到重複。但無法找到一種簡單的方法來刪除重複項,同時保持原始順序(因爲使用排序 - 失去原來的順序)。通過Unix shell腳本查找並刪除重複的字符串。如何?
例子:腳本調用dedupe.sh
運行示例:
dedupe.sh
cat dog cat bird fish bear dog
結果:cat dog bird fish bear
你說的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
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"
這不是那種東西shell腳本是專爲。你在使用哪種外殼?你應該爲此添加一個perl標籤,有人會用perl中的解決方案來彈出。 – 2013-03-18 00:48:31
這是在文件中?如果是,請使用'uniq'。 – squiguy 2013-03-18 00:50:49