#3385: Add unique option for uniq command (#3754)

* Added -u arg for command uniq.

* Update uniq.rs

Co-authored-by: JT <jonathandturner@users.noreply.github.com>
This commit is contained in:
Matheus 2021-07-09 16:27:35 -03:00 committed by GitHub
parent 11cb5ed10e
commit 5bc7a1f435
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 34 additions and 3 deletions

View File

@ -23,6 +23,7 @@ impl WholeStreamCommand for Uniq {
"Ignore differences in case when comparing",
Some('i'),
)
.switch("unique", "Only return unique values", Some('u'))
}
fn usage(&self) -> &str {
@ -49,6 +50,11 @@ impl WholeStreamCommand for Uniq {
example: "echo [1 2 2] | uniq -d",
result: Some(vec![UntaggedValue::int(2).into()]),
},
Example {
description: "Only print unique lines lines",
example: "echo [1 2 2] | uniq -u",
result: Some(vec![UntaggedValue::int(1).into()]),
},
Example {
description: "Ignore differences in case when comparing",
example: "echo ['hello' 'goodbye' 'Hello'] | uniq -i",
@ -95,6 +101,7 @@ fn uniq(args: CommandArgs) -> Result<ActionStream, ShellError> {
let should_show_count = args.has_flag("count");
let show_repeated = args.has_flag("repeated");
let ignore_case = args.has_flag("ignore-case");
let only_uniques = args.has_flag("unique");
let input = args.input;
let uniq_values = {
let mut counter = IndexMap::<nu_protocol::Value, usize>::new();
@ -109,14 +116,18 @@ fn uniq(args: CommandArgs) -> Result<ActionStream, ShellError> {
counter
};
let mut values_vec_deque = VecDeque::new();
let values = if show_repeated {
let mut values = if show_repeated {
uniq_values.into_iter().filter(|i| i.1 > 1).collect::<_>()
} else {
uniq_values
};
if only_uniques {
values = values.into_iter().filter(|i| i.1 == 1).collect::<_>();
}
let mut values_vec_deque = VecDeque::new();
if should_show_count {
for item in values {
use nu_protocol::Value;

View File

@ -170,6 +170,26 @@ fn uniq_counting() {
assert_eq!(actual.out, "1");
}
#[test]
fn uniq_unique() {
let actual = nu!(
cwd: "tests/fixtures/formats", pipeline(
r#"
echo [1 2 3 4 1 5]
| uniq --unique
"#
));
let expected = nu!(
cwd: "tests/fixtures/formats", pipeline(
r#"
echo [2 3 4 5]
"#
));
print!("{}", actual.out);
print!("{}", expected.out);
assert_eq!(actual.out, expected.out);
}
#[test]
fn uniq_simple_vals_ints() {
let actual = nu!(