Find
搜尋任意文件,但只在結果中列出一次匹配項
我想搜尋任意文件/目錄名稱,但只想在同一位置列出包含搜尋字元串的文件路徑一次。特別是不是目錄中的每個文件都與搜尋字元串匹配。
這是一個範例,
locate -i flatpak
列表:/etc/flatpak /etc/dbus-1/system.d/org.freedesktop.Flatpak.SystemHelper.conf /etc/flatpak/remotes.d /etc/profile.d/flatpak.sh /home/simon/.cache/gnome-software/flatpak/installation-tmp/repo/objects/74 /home/simon/.cache/gnome-software/flatpak/installation-tmp/repo/objects/75 /home/simon/.cache/gnome-software/flatpak/installation-tmp/repo/objects/76 /home/simon/.cache/gnome-software/flatpak/installation-tmp/repo/objects/77 /home/simon/.cache/gnome-software/flatpak/installation-tmp/repo/objects/78 /home/simon/.cache/gnome-software/flatpak/installation-tmp/repo/objects/79 /home/simon/.cache/gnome-software/flatpak/installation-tmp/repo/objects/7a /home/simon/.cache/gnome-software/flatpak/installation-tmp/repo/objects/7b /home/simon/.cache/gnome-software/flatpak/installation-tmp/repo/objects/7c /home/simon/.cache/gnome-software/flatpak/installation-tmp/repo/objects/7d /var/lib/flatpak /var/lib/flatpak/.changed /var/lib/flatpak/.removed /var/lib/flatpak/app /var/lib/flatpak/appstream /var/lib/flatpak/exports /var/lib/flatpak/repo /var/lib/flatpak/runtime
但我想要這樣的搜尋結果:
/etc/flatpak /etc/dbus-1/system.d/org.freedesktop.Flatpak.SystemHelper.conf /etc/profile.d/flatpak.sh /home/simon/.cache/gnome-software/flatpak /var/lib/flatpak
哪種工具最適合這個?
locate
,find
,fd-find
?
聽起來您只想
flatpak
在文件名中搜尋(而不是在其他路徑組件中),因此您可以使用-b
/--basename
選項:所以:
locate -ib flatpak
另一種方法可能是使用
-r
/--regex
選項並編寫:locate -ir 'flapak[^/]*$'
除了文件路徑的結尾之外,
flatpak
後面還有任意數量的字元。/
但是,這可能會錯過 . 之後具有非字元(在目前語言環境中)的文件名
flatpak
。
您可以使用
sed
刪除 pattern 之後的所有內容flatpak
,然後您可以對輸出進行排序並僅列印唯一的行:locate -i flatpak | sed -E -e 's/(flatpak\/?).*/\1/i' -e 's/\/$//' | sort | uniq