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

my_list.txt:

/tmp
/var/tmp

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


当前回答

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,而不是输出。

关于以下解决方案:

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.)

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

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  
if grep -q "$Filename$" my_list.txt
   then
     echo "exist"
else 
     echo "not exist"
fi

我正在寻找一种方法来在终端中做到这一点,并在正常的“grep行为”中过滤行。把你的字符串放在strings.txt文件中:

string1
string2
...

然后你可以构建一个正则表达式(string1|string2|…)并使用它进行过滤:

cmd1 | grep -P "($(cat strings.txt | tr '\n' '|' | head -c -1))" | cmd2

编辑:以上只适用于你不使用任何正则表达式字符,如果需要转义,它可以这样做:

cat strings.txt | python3 -c "import re, sys; [sys.stdout.write(re.escape(line[:-1]) + '\n') for line in sys.stdin]" | ...