我有一个包含目录名的文件:
my_list.txt:
/tmp
/var/tmp
如果目录名已经存在于文件中,我想在添加目录名之前检入Bash。
我有一个包含目录名的文件:
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
其他回答
最简单的方法是:
isInFile=$(cat file.txt | grep -c "string")
if [ $isInFile -eq 0 ]; then
#string not contained in file
else
#string is in file at least once
fi
Grep -c将返回该字符串在文件中出现的次数。
if grep -q "$Filename$" my_list.txt
then
echo "exist"
else
echo "not exist"
fi
grep -E "(string)" /path/to/file || echo "no match found"
-E选项使grep使用正则表达式
关于以下解决方案:
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的解决方案,对我来说是有效的:
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