【问题标题】:Checking if a multi-line string exist in a file检查文件中是否存在多行字符串
【发布时间】:2021-10-07 04:11:41
【问题描述】:
我想制作一个 bash 脚本来检查文件中是否已经存在每一行多行字符串。
我已经写了一些代码,但我不确定它是否可以工作:
str="
this is
a multiple
line
string"
while read -r f; do
while read -r s: do
if [ $r == $s ]; then break; fi
done
done << some_file.txt
有什么想法让它发挥作用吗?
【问题讨论】:
-
第一次检查语法时,请考虑粘贴整个代码(包括 shebang)@ShellCheck,然后进行建议的更改;至于评论... 我不确定它会起作用 ...您是否尝试过运行代码?你得到了什么结果?
标签:
string
bash
string-comparison
【解决方案1】:
感谢您的代码创意。看来计划的代码已经超出了我的编程技能,我无法独自继续它;-)
注意:要明确:需要代码来帮助人们在没有 NAG 屏幕的情况下使 Sublime3 工作以供个人和爱好使用
是否有可能让它像类型化算法一样工作:
注意:圆形分支中给出的变量名称作为示例给出
我。将预期值(用## BLOCK HEADER 和## BLOCK END 分隔)读入变量(预期)
二。将文件内容读入临时变量(in_file)
三。检查(in_file)中的块分隔符是否存在
-
如果块分隔符不存在,则将(预期)的内容添加到文件中并结束
-
如果存在块分隔符,则将块的条目读入变量(块)并将其内容(每一行)与(预期)的内容进行比较
a) 应从以后的处理中跳过相同的(现有)条目
b) 如果缺少任何条目,则将其导出到变量中(缺少)
c) 到达块结束分隔符后,将(missing) 中的条目添加到(in_file) 的现有块中并结束
?
【解决方案2】:
我喜欢 case 的声明。
$ cat script
str1="
this is
a multiple
line
string"
str2="$1"
f="$(<$0)"
case "$f" in
*"$str1"*) echo "String 1 exists" ;;
*) echo "String 1 not found" ;;
esac
case "$f" in
*"$str2"*) echo "String 2 exists" ;;
*) echo "String 2 not found" ;;
esac
$ ./script esac
String 1 exists
String 2 exists
$ ./script foo
String 1 exists
String 2 not found
【解决方案3】:
这可能是bash中的解决方案:
- 将字符串行读入数组。
- 然后,对于数组中的每个字符串行:
- 检查文件是否包含与该字符串行相等的整行。
- 检查失败后停止遍历阵列。
#!/bin/bash
file="$1"
names="
this is
a multiple
line
string"
# Read string lines into an array
readarray -t <<< $names
# Walk array of lines
all_strings_found=true
for string in "${MAPFILE[@]}"; do
if ! grep -q "^$string$" $file; then
echo "'"$string"'" "not found"
all_strings_found=false
break
fi
done
if [ "$all_strings_found" == true ]; then
echo "---> All strings found"
else
echo "---> NOT all strings found"
fi
【解决方案4】:
可以是 perl 单行:
if perl -0777 -sne '/$text/ or exit 1' -- -text="$str" "$file"
then
echo Found
else
echo not found
fi
-0777 选项将整个文件放入内存中
【解决方案5】:
如果您可以将整个文件两次加载到内存中,这是一个技巧:
str="
this is
a multiple
line
string"
# Read the whole file in variable
content=$(<some_file.txt)
# Replace str to nothing in content
repr=${content/${str}}
# Check if it's the same.
if [[ "$content" != "$repr" ]]; then
# If it's not, means content contains str and it was removed.
echo "Contains"
fi