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

my_list.txt:

/tmp
/var/tmp

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


当前回答

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

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

其他回答

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

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

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

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  
grep -Fxq "String to be found" | ls -a

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

更简单的方法:

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

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