【问题标题】:Find file names in other Bash files using grep使用 grep 在其他 Bash 文件中查找文件名
【发布时间】:2014-06-20 14:39:33
【问题描述】:

如何遍历输入文本文件中的 Bash 文件名列表,并为每个文件名在目录中查找每个文件(以查看文件名是否包含在文件中)并将所有文件名输出为文本没有在任何文件中找到?

#!/bin/sh

# This script will be used to output any unreferenced bash files
# included in the WebAMS Project
# Read file path of bash files and file name input

SEARCH_DIR=$(awk -F "=" '/Bash Dir/ {print $2}' bash_input.txt)
FILE_NAME=$(awk -F "=" '/Input File/ {print $2}' bash_input.txt)

echo $SEARCH_DIR
echo $FILE_NAME

exec<$FILE_NAME

while read line
do
    echo "IN WHILE"
    if (-z "$(grep -lr $line $SEARCH_DIR)"); then
        echo "ENTERED"
        echo $filename
    fi
done

【问题讨论】:

  • 我重新格式化了脚本。如果您将一行缩进四个字符,它将被视为 code 并进行相应的格式化。该程序还将进行一些语法突出显示。这比尝试在每一行周围放回引号更容易更好。
  • 谢谢,我只是想弄清楚这一点。谢谢你这样做。

标签: bash file unix grep output


【解决方案1】:

将此保存为search.sh,根据您的环境更新SEARCH_DIR

#!/bin/bash

SEARCH_DIR=some/dir/here

while read filename
do
        if [ -z "$(grep -lr $filename $SEARCH_DIR)" ]
        then
                echo $filename
        fi
done

然后:

chmod +x 搜索.sh ./search.sh 文件-i-could-not-find.txt

【讨论】:

  • 我不断收到:./BashRemovalTool.sh: line 19: -z: command not found,它指的是 if 语句中的 grep。我将在我的问题中发布我上面的代码。
  • 您将括号放在if 之后。它们应该是方括号。
【解决方案2】:

可以通过grepfind 命令实现,

while read -r line; do (find . -type f -exec grep -l "$line" {} \;); done < file

while read -r line; do grep -rl "$line"; done < file

-r --> 递归
-l --> files-with-matches(显示包含搜索字符串的文件名)

它将读取输入文件中存在的所有文件名并搜索包含读取的文件名的文件名。如果找到,则返回相应的文件名。

【讨论】:

  • 他想搜索包含文件名的文件,而不是按文件名搜索。
  • 是的,我想在每个文件中搜索文件名,然后将它们从应该输出的文件名列表中删除。肖恩是对的。
  • 为什么要使用find 而不是grep -r
  • 你的意思是$ while read -r line; do grep -rl "$line"; done &lt; file。是的,当然:-)
【解决方案3】:

您在 if 语句中使用了常规括号而不是方括号。

方括号是 test 命令。您正在运行测试(在您的情况下,字符串的长度是否为零。如果测试成功,[ ... ] 命令返回零退出代码。if 语句看到该退出代码并运行then 语句的 if 子句。否则,如果存在 else 语句,则改为运行。

因为[ .. ] 实际上是命令,您必须在每一边留一个空白区域。

if [ -z "$string" ]

错误

if [-z "$string"]  # Need white space around the brackets

有点错误

if [ -z $sting ]   # Won't work if "$string" is empty or contains spaces

顺便说一下,以下是一样的:

if test -z "$string"

if [ test -z "$string" ]

小心grep 命令。如果返回的字符串中有空格或换行符,它可能不会像你想象的那样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多