如何测试Bash文件中是否存在字符串?
我有一个包含目录名称的文件:
my_list.txt
:
/tmp
/var/tmp
如果该名称已存在于文件中,我会在添加目录名称之前检入Bash。
grep -Fxq "$FILENAME" my_list.txt
如果名称被找到,则退出状态为0(真),否则为1(假),因此:
if grep -Fxq "$FILENAME" my_list.txt
then
# code if found
else
# code if not found
fi
以下是grep
手册页的相关部分:
grep [options] PATTERN [FILE...]
-F, --fixed-strings
Interpret PATTERN as a list of fixed strings, separated by new-
lines, any of which is to be matched.
-x, --line-regexp
Select only those matches that exactly match the whole line.
-q, --quiet, --silent
Quiet; do not write anything to standard output. Exit immedi-
ately with zero status if any match is found, even if an error
was detected. Also see the -s or --no-messages option.
关于以下解决方案:
grep -Fxq "$FILENAME" my_list.txt
如果你想知道(就像我做过的那样) -Fxq
意思是简单的英语F
会影响PATTERN的解释方式(固定字符串而不是正则表达式), x
匹配整行, q
shhhhh ...最小打印
从man文件中:
-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.)
我脑海中的三种方法:
1)在路径中测试一个名称(我不确定这可能是你的情况)
ls -a "path" | grep "name"
2)对文件中的字符串进行简短测试
grep -R "string" "filepath"
3)使用正则表达式更长的bash脚本:
#!/bin/bash
declare file="content.txt"
declare regex="s+strings+"
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
如果您必须使用循环测试文件内容中的多个字符串 ,例如在任何cicle上更改正则表达式,这应该会更快 。
上一篇: How to test if string exists in file with Bash?
下一篇: How to obtain the number of CPUs/cores in Linux from the command line?