Tor*_*ren 304 string bash file
我有一个包含目录名称的文件:
my_list.txt :
/tmp
/var/tmp
我想在我添加目录名之前检查Bash,如果该名称已存在于文件中.
Tho*_*mas 595
grep -Fxq "$FILENAME" my_list.txt
如果找到名称,则退出状态为0(true),否则为1(false),因此:
if grep -Fxq "$FILENAME" my_list.txt
then
    # code if found
else
    # code if not found
fi
以下是手册页grep的相关部分:
grep [options] PATTERN [FILE...]
Kuf*_*Kuf 86
关于以下解决方案:
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.)
Luc*_*one 38
我心中有三种方法:
1)对路径中的名称进行简短测试(我不确定这可能是您的情况)
ls -a "path" | grep "name"
2)对文件中的字符串进行简短测试
grep -R "string" "filepath"
3)使用正则表达式的更长的bash脚本:
#!/bin/bash
declare file="content.txt"
declare regex="\s+string\s+"
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上的正则表达式,这应该更快.
imw*_*nxu 16
更简单的方法:
if grep "$filename" my_list.txt > /dev/null
then
   ... found
else
   ... not found
fi
提示:/dev/null如果您想要命令的退出状态而不是输出,则发送到.
GTo*_*rov 11
这是搜索和评估字符串或部分字符串的快速方法:
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
小智 9
最简单最简单的方法是:
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将返回字符串在文件中出现次数的计数.
grep -E "(string)" /path/to/file || echo "no match found"
-E 选项使 grep 使用正则表达式
如果我理解你的问题,这应该做你需要的.
在一行中:check="/tmp/newdirectory"; [[ -n $(grep "^$check\$" my_list.txt) ]] && echo "dir already listed" || echo "$check" >> my_list.txt
由于某种原因,@Thomas 的解决方案对我不起作用,但我有更长的带有特殊字符和空格的字符串,所以我只是更改了参数,如下所示:
if grep -Fxq 'string you want to find' "/path/to/file"; then
    echo "Found"
else
    echo "Not found"
fi
希望它可以帮助某人