我有一个包含目录名的文件:
my_list.txt:
/tmp
/var/tmp
如果目录名已经存在于文件中,我想在添加目录名之前检入Bash。
我有一个包含目录名的文件:
my_list.txt:
/tmp
/var/tmp
如果目录名已经存在于文件中,我想在添加目录名之前检入Bash。
当前回答
if grep -q "$Filename$" my_list.txt
then
echo "exist"
else
echo "not exist"
fi
其他回答
与其他答案略有相似,但没有分叉,条目可以包含空格
contains() {
[[ " ${list[@]} " =~ " ${1} " ]] && echo 'contains' || echo 'does not contain'
}
IFS=$'\r\n' list=($(<my_list.txt))
对于my_list。txt
/tmp
/var/tmp
/Users/usr/dir with spaces
这些测试
contains '/tmp'
contains '/bin'
contains '/var/tmp'
contains '/Users/usr/dir with spaces'
contains 'dir with spaces'
返回
exists
does not exist
exists
exists
does not exist
如果我没有理解错你的问题,这个应该可以满足你的需要。
您可以通过$check变量指定要添加的目录 如果目录已经在列表中,则输出"dir already listed" 如果目录还不在列表中,它会被追加到my_list.txt
一行:check="/tmp/newdirectory";[[-n $(grep "^$check\$" my_list.txt)]]] && echo "dir already listed" || echo "$check" >> my_list.txt
grep -Fxq "String to be found" | ls -a
Grep将帮助您检查内容 ls将列出所有的文件
我正在寻找一种方法来在终端中做到这一点,并在正常的“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]" | ...
我的版本使用fgrep
FOUND=`fgrep -c "FOUND" $VALIDATION_FILE`
if [ $FOUND -eq 0 ]; then
echo "Not able to find"
else
echo "able to find"
fi