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

my_list.txt:

/tmp
/var/tmp

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


当前回答

更简单的方法:

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

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

其他回答

关于以下解决方案:

grep -Fxq "$FILENAME" my_list.txt

如果你想知道(像我一样)-Fxq在通俗英语中是什么意思:

F:影响PATTERN的解释方式(固定字符串而不是正则表达式) x:匹配整行 问:嘘……最小的印刷

从男子档案中可以看出:

-F, --fixed-strings
    Interpret  PATTERN  as  a  list of fixed strings, separated by newlines, any of which is to be matched.
    (-F is specified by POSIX.)
-x, --line-regexp
    Select only those matches that exactly match the whole line.  (-x is specified by POSIX.)
-q, --quiet, --silent
    Quiet; do not write anything to standard output.  Exit immediately with zero status  if  any  match  is
          found,  even  if  an error was detected.  Also see the -s or --no-messages option.  (-q is specified by
          POSIX.)
grep -E "(string)" /path/to/file || echo "no match found"

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

我的版本使用fgrep

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

与其他答案略有相似,但没有分叉,条目可以包含空格

contains() {
    [[ " ${list[@]} " =~ " ${1} " ]] && echo 'contains' || echo 'does not contain'
}

IFS=$'\r\n' list=($(<my_list.txt))

对于my_list。txt

/tmp
/var/tmp
/Users/usr/dir with spaces

这些测试

contains '/tmp'
contains '/bin'
contains '/var/tmp'
contains '/Users/usr/dir with spaces'
contains 'dir with spaces'

返回

exists
does not exist
exists
exists
does not exist

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

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