如何使用grep只获取没有路径的文件名 [英] How to get only filenames without Path by using grep

查看:19
本文介绍了如何使用grep只获取没有路径的文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了以下问题.

我正在做一个类似的 grep:

I´m doing a grep like:

$command = grep -r -i --include=*.cfg 'host{'/omd/sites/mesh/etc/icinga/conf.d/objects

$command = grep -r -i --include=*.cfg 'host{' /omd/sites/mesh/etc/icinga/conf.d/objects

我得到以下输出:

/omd/sites/mesh/etc/icinga/conf.d/objects/testsystem/test1.cfg:define host{
/omd/sites/mesh/etc/icinga/conf.d/objects/testsystem/test2.cfg:define host{
/omd/sites/mesh/etc/icinga/conf.d/objects/testsystem/test3.cfg:define host{
...

对于所有 *.cfg 文件.

for all *.cfg files.

使用 exec($command,$array)

我以数组的形式传递了结果.

I passed the result in an array.

是否可以只获取文件名作为 grep 命令的结果.

Is it possible to get only the filenames as result of the grep-command.

我尝试了以下方法:

$Command=    grep -l -H -r -i --include=*.cfg 'host{' /omd/sites/mesh/etc/icinga/conf.d/objects

但我得到了相同的结果.

but I got the same result.

我知道论坛上存在类似的主题.(如何在 linux 上使用 grep 仅显示文件名(无内联匹配)?),但该解决方案不起作用.

I know that on the forum a similar topic exists.(How can I use grep to show just filenames (no in-line matches) on linux?), but the solution doesn´t work.

使用exec($Command,$result_array)",我尝试获取包含结果的数组.提到的解决方案都有效,但我无法使用 exec() 获得 resultarray.

With "exec($Command,$result_array)" I try to get an array with the results. The mentioned solutions works all, but I can´t get an resultarray with exec().

有人可以帮我吗?

推荐答案

另一种更简单的解决方案:

Yet another simpler solution:

grep -l whatever-you-want | xargs -L 1 basename

或者您可以避免使用 xargs 并使用子shell 代替,如果您使用的不是 GNU coreutils 的旧版本:

or you can avoid xargs and use a subshell instead, if you are not using an ancient version of the GNU coreutils:

basename -a $(grep -l whatever-you-want)

basename 是获取没有路径的文件名的 bash 直接解决方案.您可能还对 dirname 感兴趣以仅获取路径.

basename is the bash straightforward solution to get a file name without path. You may also be interested in dirname to get the path only.

GNU Coreutils 基本名称文档

这篇关于如何使用grep只获取没有路径的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆