我有一个包含目录名的文件:

my_list.txt:

/tmp
/var/tmp

如果目录名已经存在于文件中,我想在添加目录名之前检入Bash。


当前回答

由于某种原因,@Thomas的解决方案对我不起作用,但我有更长的字符串和特殊字符和空格,所以我只是像这样更改参数:

if grep -Fxq 'string you want to find' "/path/to/file"; then
    echo "Found"
else
    echo "Not found"
fi

希望它能帮助到别人

其他回答

我正在寻找一种方法来在终端中做到这一点,并在正常的“grep行为”中过滤行。把你的字符串放在strings.txt文件中:

string1
string2
...

然后你可以构建一个正则表达式(string1|string2|…)并使用它进行过滤:

cmd1 | grep -P "($(cat strings.txt | tr '\n' '|' | head -c -1))" | cmd2

编辑:以上只适用于你不使用任何正则表达式字符,如果需要转义,它可以这样做:

cat strings.txt | python3 -c "import re, sys; [sys.stdout.write(re.escape(line[:-1]) + '\n') for line in sys.stdin]" | ...

如果您只是想检查一行是否存在,则不需要创建文件。例如,

if grep -xq "LINE_TO_BE_MATCHED" FILE_TO_LOOK_IN ; then
  # code for if it exists
else
  # code for if it does not exist
fi  

如果我没有理解错你的问题,这个应该可以满足你的需要。

您可以通过$check变量指定要添加的目录 如果目录已经在列表中,则输出"dir already listed" 如果目录还不在列表中,它会被追加到my_list.txt

一行:check="/tmp/newdirectory";[[-n $(grep "^$check\$" my_list.txt)]]] && echo "dir already listed" || echo "$check" >> my_list.txt

更简单的方法:

if grep "$filename" my_list.txt > /dev/null
then
   ... found
else
   ... not found
fi

提示:如果你想要命令的退出状态,发送到/dev/null,而不是输出。

我认为有三种方法:

1)路径中名称的简短测试(我不确定这可能是你的情况)

ls -a "path" | grep "name"

2)文件中字符串的简短测试

grep -R "string" "filepath"

3)更长的bash脚本使用regex:

#!/bin/bash

declare file="content.txt"
declare regex="\s+string\s+"

declare file_content=$( cat "${file}" )
if [[ " $file_content " =~ $regex ]] # please note the space before and after the file content
    then
        echo "found"
    else
        echo "not found"
fi

exit

如果您必须使用循环测试文件内容上的多个字符串,例如在任何循环中更改正则表达式,那么这应该更快。