diff options
author | Tim Ledbetter <timledbetter@gmail.com> | 2023-05-30 17:51:18 +0100 |
---|---|---|
committer | Andreas Kling <kling@serenityos.org> | 2023-05-31 06:04:48 +0200 |
commit | ad851706ab434abf1cccd94955d919747f86a987 (patch) | |
tree | 42c8b8a5a319aa6463452a8b12af3b142137946d /Userland/Utilities/pgrep.cpp | |
parent | f95e6ee8494766adb4f9fd73932ae0e5de530bbc (diff) | |
download | serenity-ad851706ab434abf1cccd94955d919747f86a987.zip |
pgrep: Add `-c` option to show the number of matches
Diffstat (limited to 'Userland/Utilities/pgrep.cpp')
-rw-r--r-- | Userland/Utilities/pgrep.cpp | 27 |
1 files changed, 16 insertions, 11 deletions
diff --git a/Userland/Utilities/pgrep.cpp b/Userland/Utilities/pgrep.cpp index 4c7fa0b29c..5cc16839dc 100644 --- a/Userland/Utilities/pgrep.cpp +++ b/Userland/Utilities/pgrep.cpp @@ -20,12 +20,14 @@ ErrorOr<int> serenity_main(Main::Arguments args) TRY(Core::System::unveil("/etc/passwd", "r")); TRY(Core::System::unveil(nullptr, nullptr)); + bool display_number_of_matches = false; auto pid_delimiter = "\n"sv; bool case_insensitive = false; bool invert_match = false; StringView pattern; Core::ArgsParser args_parser; + args_parser.add_option(display_number_of_matches, "Suppress normal output and print the number of matching processes", "count", 'c'); args_parser.add_option(pid_delimiter, "Set the string used to delimit multiple pids", "delimiter", 'd', nullptr); args_parser.add_option(case_insensitive, "Make matches case-insensitive", "ignore-case", 'i'); args_parser.add_option(invert_match, "Select non-matching lines", "invert-match", 'v'); @@ -51,20 +53,23 @@ ErrorOr<int> serenity_main(Main::Arguments args) } } - quick_sort(matches); + if (display_number_of_matches) { + outln("{}", matches.size()); + } else { + quick_sort(matches); + auto displayed_at_least_one = false; + for (auto& match : matches) { + if (displayed_at_least_one) + out("{}{}"sv, pid_delimiter, match); + else + out("{}"sv, match); - auto displayed_at_least_one = false; - for (auto& match : matches) { - if (displayed_at_least_one) - out("{}{}"sv, pid_delimiter, match); - else - out("{}"sv, match); + displayed_at_least_one = true; + } - displayed_at_least_one = true; + if (displayed_at_least_one) + outln(); } - if (displayed_at_least_one) - outln(); - return matches.size() > 0 ? 0 : 1; } |