0

这是 Bash 函数的后续问题,它检查文件中是否有文本,如果没有则添加文本

我正在尝试创建一个 bash 函数来检查文件中是否包含文本。如果文本在文件中,则不要文本。如果是添加文本。我的代码是

#!/bin/bash
#Function that checks if text (ARGV1) is in a document (ARGV2). Please make ARGV1 an array of strings, with each new line a new entry in the array.

declare -a inputText=("[test]" "host=dynamic" "disallow=all" "allow=alaw" "allow=ulaw" "type=friend" "context=test" "secret=test")

function docCheckNReplace {
    local text=$1
    local document=$2
    echo $document
    local textLen=${#text[@]}
    for ((i=0; i<textLen; i++)); do
        if grep -q "${text[$i]}" $document; then
            echo 'found'
            echo ${test[$i]} 'was found in' $document
        else
            echo 'not found'
            echo ${test[$i]} >> $document
        fi
    done
}
docCheckNReplace ${inputText[@]} /home/kam/Documents/TextingSed.txt

现在,每当我回显输入文件路径参数时,它都会返回“host=dynamic”。

当我将第一个参数设置为 inputText 而不是 ${inputText[@]} 它工作正常。

有人有什么想法吗?

谢谢 :)

4

1 回答 1

2

不要将搜索字符串作为第一个参数传递,而是将其作为参数 2 及以上的 vararg 传递。无论编程语言如何,可变数量的参数都必须放在最后。

字符串文字用单引号编写,以有效地避免解析潜在的变量/子外壳扩展语法。

在变量周围添加双引号。

使用printf而不是echo在使用混合文字和变量格式化字符串时使用。

使用-F选项 withgrep搜索纯文本,而不是将搜索字符串解释为正则表达式。

#!/usr/bin/env bash

#Function that checks if texts (vararg ARGV2) is in a document (ARGV1).
#Please make ARGV2 an array of strings, with each new line a new entry in the array.

declare -a inputText=('[test]' 'host=dynamic' 'disallow=all' 'allow=alaw' 'allow=ulaw' 'type=friend' 'context=test' 'secret=test')

function docCheckNReplace {
    local document="$1"
    # Shift out document from arguments array
    # Now it only contains vararg search strings
    shift

    echo "$document"
    for search_string; do
        if grep -qF "$search_string" "$document"; then
            echo 'found'
            printf '%s was found in %s.\n' "$search_string" "$document"
        else
            echo 'not found'
            echo "$search_string" >> "$document"
        fi
    done
}

docCheckNReplace '/home/kam/Documents/TextingSed.txt' "${inputText[@]}"
于 2020-03-27T16:17:53.390 回答