我在一个名为files. 我必须从此目录中读取每个 .txt 文件:
abc123.txt
abc234.txt
abc345.txt
abc.txt
def123.txt
def234.txt
def345.txt
Run Code Online (Sandbox Code Playgroud)
例如,当我./filter.sh abc在终端中输入时,它会搜索.txt名称包含abc.
#!/bin/bash
input1=$1
find ./files -type f -name "*$input1*.txt"
Run Code Online (Sandbox Code Playgroud)
我的输出看起来像这样
./files/abc345.txt
./files/abc234.txt
./files/abc123.txt
./files/abc.txt
Run Code Online (Sandbox Code Playgroud)
我做对了吗?而且,是否可以不显示./files/在输出中?为什么我的输出显示abc345, abc234,abc123而不是abc123, abc234, abc345?
是的,这很好。但是,当您更熟悉 时find,您将直接在命令行上执行此操作(而不是通过 shellscript)。我经常使用 shellscripts,但主要用于更大的任务(几个命令行)。
您可以删除找到它的起点:
find ./files -type f -name "*$input1*.txt" -printf "%P\n"
Run Code Online (Sandbox Code Playgroud)
最后,您可以在之后对文件进行排序:
find ./files -type f -name "*$input1*.txt" -printf "%P\n" | sort
Run Code Online (Sandbox Code Playgroud)
如果数量少或文件小,您可以将内容写入终端
find ./files -type f -name "*$input1*.txt" -exec echo "--- {}:" \; -exec cat {} \;
Run Code Online (Sandbox Code Playgroud)
输出可以通过以下方式重定向到文件 > output.txt
find ./files -type f -name "*$input1*.txt" -exec echo "--- {}:" \; -exec cat {} \; > output.txt
Run Code Online (Sandbox Code Playgroud)
水平滚动以查看该行的末尾。
如果有很多文件或一些大文件,最好使用较少的文件或您最喜欢的文本编辑器查看文件,
find ./files -type f -name "*$input1*.txt" -exec less {} \;
Run Code Online (Sandbox Code Playgroud)
并从每个文件之间的 less 中以 'q' 退出。
find 相对 ls
find是一个可以在目录树中[递归地]查找文件的高级工具,它有很多选项。学习可以用它做什么需要很长时间。查看man find或者更简单,通过互联网查看教程。
ls是一个更简单的工具,它在一个目录级别(通常是当前级别)列出文件。它也有很多选项,但很容易从命令行使用。请注意,这ls在 shellscripts中可能会以一种令人困惑的方式表现出来,特别是在与其他命令组合时。见man ls。
您可以这样做并遵循@sudodus 建议来改进输出。
但是find对于您的用例来说有点矫枉过正,您可以简单地使用ls:
ls -1 files/abc*
Run Code Online (Sandbox Code Playgroud)
要获取目录名称:
(cd files && ls -1 abc*)
Run Code Online (Sandbox Code Playgroud)