我有一个包含目录名的文件:
my_list.txt:
/tmp
/var/tmp
如果目录名已经存在于文件中,我想在添加目录名之前检入Bash。
我有一个包含目录名的文件:
my_list.txt:
/tmp
/var/tmp
如果目录名已经存在于文件中,我想在添加目录名之前检入Bash。
当前回答
我认为有三种方法:
1)路径中名称的简短测试(我不确定这可能是你的情况)
ls -a "path" | grep "name"
2)文件中字符串的简短测试
grep -R "string" "filepath"
3)更长的bash脚本使用regex:
#!/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
如果您必须使用循环测试文件内容上的多个字符串,例如在任何循环中更改正则表达式,那么这应该更快。
其他回答
如果您只是想检查一行是否存在,则不需要创建文件。例如,
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
我认为有三种方法:
1)路径中名称的简短测试(我不确定这可能是你的情况)
ls -a "path" | grep "name"
2)文件中字符串的简短测试
grep -R "string" "filepath"
3)更长的bash脚本使用regex:
#!/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
如果您必须使用循环测试文件内容上的多个字符串,例如在任何循环中更改正则表达式,那么这应该更快。
grep -E "(string)" /path/to/file || echo "no match found"
-E选项使grep使用正则表达式
最简单的方法是:
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将返回该字符串在文件中出现的次数。
与其他答案略有相似,但没有分叉,条目可以包含空格
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