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

my_list.txt:

/tmp
/var/tmp

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


当前回答

grep -Fxq "String to be found" | ls -a

Grep将帮助您检查内容 ls将列出所有的文件

其他回答

grep -Fxq "String to be found" | ls -a

Grep将帮助您检查内容 ls将列出所有的文件

下面是一个快速搜索和计算字符串或部分字符串的方法:

if grep -R "my-search-string" /my/file.ext
then
    # string exists
else
    # string not found
fi

你也可以先测试,如果该命令只通过运行返回任何结果:

grep -R "my-search-string" /my/file.ext

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

if grep -Fxq 'string you want to find' "/path/to/file"; then
    echo "Found"
else
    echo "Not found"
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

一个无grep的解决方案,对我来说是有效的:

MY_LIST=$( cat /path/to/my_list.txt )



if [[ "${MY_LIST}" == *"${NEW_DIRECTORY_NAME}"* ]]; then
  echo "It's there!"
else
echo "its not there"
fi

基于: https://stackoverflow.com/a/229606/3306354