From 952c0dc2a02e92ba6380cba7fde8e4f9f00af257 Mon Sep 17 00:00:00 2001 From: Sergey Bugaev Date: Sat, 28 Nov 2020 14:21:31 +0300 Subject: [PATCH] Userland: Implement find -name clause Closes https://github.com/SerenityOS/serenity/issues/4191 --- Base/usr/share/man/man1/find.md | 6 ++++++ Userland/find.cpp | 24 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/Base/usr/share/man/man1/find.md b/Base/usr/share/man/man1/find.md index 1e89fa0d3c..f7f2c57581 100644 --- a/Base/usr/share/man/man1/find.md +++ b/Base/usr/share/man/man1/find.md @@ -35,6 +35,10 @@ specified commands, a `-print` command is implicitly appended. * `-size number[c]`: Checks if the file has the given size in 512-byte blocks, rounded up. If the size is followed by the `c` character, checks if the file has the given size in bytes. +* `-name pattern`: Checks if the file name matches the given global-style + pattern (case sensitive). +* `-iname pattern`: Checks if the file name matches the given global-style + pattern (case insensitive). * `-print`: Outputs the file path, followed by a newline. Always evaluates to true. * `-print0`: Outputs the file path, followed by a zero byte. Always evaluates to @@ -62,6 +66,8 @@ $ find -type d $ find /tmp "(" -type s -o -user anon ")" -exec rm "{}" ";" # Concatenate files with weird characters in their names: $ find -type f -print0 | xargs -0 cat +# Find files with the word "config" in their name: +$ find -name \*config\* ``` ## See also diff --git a/Userland/find.cpp b/Userland/find.cpp index baee2887a0..4d581663bc 100644 --- a/Userland/find.cpp +++ b/Userland/find.cpp @@ -24,6 +24,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +#include #include #include #include @@ -212,6 +213,25 @@ private: bool m_is_bytes { false }; }; +class NameCommand : public Command { +public: + NameCommand(const char* pattern, CaseSensitivity case_sensitivity) + : m_pattern(pattern) + , m_case_sensitivity(case_sensitivity) + { + } + +private: + virtual bool evaluate(const char* file_path) const override + { + LexicalPath path { file_path }; + return path.basename().matches(m_pattern, m_case_sensitivity); + } + + StringView m_pattern; + CaseSensitivity m_case_sensitivity { CaseSensitivity::CaseSensitive }; +}; + class PrintCommand final : public Command { public: PrintCommand(char terminator = '\n') @@ -335,6 +355,10 @@ static OwnPtr parse_simple_command(char* argv[]) return make(argv[++optind]); } else if (arg == "-size") { return make(argv[++optind]); + } else if (arg == "-name") { + return make(argv[++optind], CaseSensitivity::CaseSensitive); + } else if (arg == "-iname") { + return make(argv[++optind], CaseSensitivity::CaseInsensitive); } else if (arg == "-print") { g_have_seen_action_command = true; return make();