繁体   English   中英

在Linux中检索目录下的特定文件

[英]Retrieve specific files under a directory in Linux

我想使用linux在目录下查看特定文件的列表。 例如说:-我的当前目录中有以下子目录

 Feb 16 00:37 a1
 Feb 16 00:38 a2
 Feb 16 00:36 a3

现在如果我做ls a* -我可以看到

bash-4.1$ ls a*
a:

a1:
123.sh  123.txt

a2:
a234.sh  a234.txt

a3:
a345.sh  a345.txt

我只想从目录中过滤掉.sh文件,所以输出应该是:-

a1:
123.sh

a2:
a234.sh

a3:
a345.sh

可能吗?

另外也可以打印sh文件的第一行吗?

下面的find命令应该为您工作:

find . -maxdepth 2 -mindepth 2 -path '*/a*/*.sh' -print -exec head -n1 {} \;

只需看看这些选项。 希望您能找到想要的东西

基本的“查找文件”命令

find / -name foo.txt -type f -print             # full command
find / -name foo.txt -type f                    # -print isn't necessary
find / -name foo.txt                            # don't have to specify "type==file"
find . -name foo.txt                            # search under the current dir
find . -name "foo.*"                            # wildcard
find . -name "*.txt"                            # wildcard
find /users/al -name Cookbook -type d           # search '/users/al'

搜索多个目录

find /opt /usr /var -name foo.scala -type f     # search multiple dirs

不区分大小写的搜索

find . -iname foo                               # find foo, Foo, FOo, FOO, etc.
find . -iname foo -type d                       # same thing, but only dirs
find . -iname foo -type f                       # same thing, but only files

查找具有不同扩展名的文件

find . -type f \( -name "*.c" -o -name "*.sh" \)                       # *.c and *.sh files
find . -type f \( -name "*cache" -o -name "*xml" -o -name "*html" \)   # three patterns

查找与模式不匹配的文件(-不)

find . -type f -not -name "*.html"     # find allfiles not ending in ".html"

通过文件中的文本查找文件(查找+ grep)

find . -type f -name "*.java" -exec grep -l StringBuffer {} \;    # find StringBuffer in all *.java files
find . -type f -name "*.java" -exec grep -il string {} \;         # ignore case with -i option
find . -type f -name "*.gz" -exec zgrep 'GET /foo' {} \;          # search for a string in gzip'd files

仅使用ls ,您可以使用以下命令获取.sh文件及其父目录:

ls -1 * | grep ":\|.sh" | grep -B1 .sh

它将提供输出:

a1:
123.sh
a2:
a234.sh
a3:
a345.sh

但是,请注意,如果您有任何名为123.sh.txt文件,则此行为将不正确。

为了在每个文件夹中打印第一个.sh文件的第一行:

head -n1 $(ls -1 */*.sh)

是的ls本身就非常容易和简单:

ls -d */*.sh

证明

在此处输入图片说明


如果您想用换行符打印它:

t $  ls -d */*.sh | tr ' ' '\n'
d1/file.sh                                                                                          
d2/file.sh                                                                                          
d3/file.sh  

要么
ls -d */*.sh | tr '/' '\\n'
输出:

d1
file.sh
d2
file.sh
d3
file.sh

对于第一行,如果需要:

t $ ls -d */*.sh | tr ' ' '\n' | head -n 1
d1/file.sh

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM