Bash函数检查文件中是否有文本,如果没有则添加文本 [英] Bash Function that checks if there is text in a file and adds the text if it is not

查看:63
本文介绍了Bash函数检查文件中是否有文本,如果没有则添加文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请注意,此问题已在我的后续问题中得到完全回答:

Please note that this question was answered fully in my follow up question here: I keep on getting host=dynamic when inputting the filepath into bash function

2018年:Hytec Holdings进行中级气动培训

2018: Intermediate Pneumatics Training at Hytec Holdings

我正在尝试创建一个函数来检查其中的文件是否包含文本.

I am trying to create a function that will check if a file in contains text.

如果文件已包含此文本,则该函数应将文本添加到文件中.

If the file already contains this text, the function should add the text to the file.

#!/bin/bash
#Function that checks if text (ARGV1) is in a document (ARGV2). Please make ARGV1 a an array of strings, with each new line a new entry in the array.
function docCheckNReplace {
    local text=$1
    local document=$2
    local textLen=${#text[@]}
    for i in {0..$(($textLen - 1))..1}; do
        echo $i
        if grep -q ${test[i]} $document; then
            echo ${test[i]} 'was found in' $document
        else
            echo ${test[i]} >> $document
        fi
    done
}

这是我到目前为止提出的.

This is what I've come up with so far.

我在运行Linux时死机了,所以我不知道问题出在哪里.

Linux freezes when I run it so I can't figure out where the problem is.

有人有任何建议吗?

谢谢:)

推荐答案

我们不必为数组索引操心;我们可以简单地逐行处理文本:

We need not bother with array indexing; we can simply process the text line by line:

    while read i; do
        echo $i
        if grep -q "$i" $document; then
            echo "$i" 'was found in' $document
        else
            echo "$i" >> $document
        fi
    done <<<$1

这篇关于Bash函数检查文件中是否有文本,如果没有则添加文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆