检查文件中是否存在多行字符串

问题描述 投票:0回答:5

我想制作一个 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

有什么想法让它发挥作用吗?

string bash string-comparison
5个回答
1
投票

如果您可以将整个文件两次加载到内存中,这里有一个技巧:

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

1
投票

这可能是

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

0
投票

它可以是 Perl 单行代码:

if perl -0777 -sne '/$text/ or exit 1' -- -text="$str" "$file"
then
    echo Found
else
    echo not found
fi

-0777
选项将整个文件放入内存中


0
投票

我喜欢

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

0
投票
没有提到

grep
,但它很可能是最快的。

str="
this is
a multiple
line
string"
grep -Fz "$str" some_file.txt
© www.soinside.com 2019 - 2024. All rights reserved.