我有一个包含目录名的文件:
my_list.txt:
/tmp
/var/tmp
如果目录名已经存在于文件中,我想在添加目录名之前检入Bash。
我有一个包含目录名的文件:
my_list.txt:
/tmp
/var/tmp
如果目录名已经存在于文件中,我想在添加目录名之前检入Bash。
当前回答
最简单的方法是:
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
下面是一个快速搜索和计算字符串或部分字符串的方法:
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
我的版本使用fgrep
FOUND=`fgrep -c "FOUND" $VALIDATION_FILE`
if [ $FOUND -eq 0 ]; then
echo "Not able to find"
else
echo "able to find"
fi
如果您只是想检查一行是否存在,则不需要创建文件。例如,
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将列出所有的文件