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

my_list.txt:

/tmp
/var/tmp

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


当前回答

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

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

其他回答

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

您可以通过$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

我的版本使用fgrep

  FOUND=`fgrep -c "FOUND" $VALIDATION_FILE`
  if [ $FOUND -eq 0 ]; then
    echo "Not able to find"
  else
    echo "able to find"     
  fi  

我认为有三种方法:

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

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

grep -E "(string)" /path/to/file || echo "no match found"

-E选项使grep使用正则表达式