string - 在bash中检查文件是否包含多行字符串

标签 string bash macos grep bsd

背景

我正在编写一个函数来附加到我的 $HOME 目录中名为 .bash.local 的文件中。

➡️ .bash.local 来自 .bash_profile

但是,我想有条件地追加到 .bash.local 当且仅当文件已包含 $BASH_CONFIGS

要记住的事情

我选择的操作系统是 MacOS Mojave,因此某些版本的命令行应用程序会有所不同(例如,Mac 上的 grepBSD grep 而不是 GNU grep)。

⚠️append_to_bash_local()

append_to_bash_local() {
    local LOCAL_BASH_CONFIG_FILE="$HOME"/.bash.local

    declare -r BASH_CONFIGS="
# TOOL_NAME - TOOL_DESCRIPTION.
# Add tool configurations here
"

    # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    # If needed, add the necessary configs in the
    # local shell configuration file.

    if ! grep "^$BASH_CONFIGS" < "$LOCAL_BASH_CONFIG_FILE" &> /dev/null; then
        # this block never runs, even if the contents of $BASH_CONFIG
        # are NOT present in $HOME/.bash.local
    fi

}

最佳答案

你很接近。不管怎样,小修正:

  • 使用零分隔的grep -Z来匹配带有换行符的模式。如果你仔细想想的话,你会发现它有点hacky,但每次都有效。
  • 使用 -q 进行 grep 使其保持静默。
  • 并且不要将文件输入到 stdin 到 grep,只需告诉 grep 文件名即可。
  • 检查文件是否存在

append_to_bash_local() {
     local LOCAL_BASH_CONFIG_FILE="$HOME"/.bash.local
     declare -r BASH_CONFIGS="
# TOOL_NAME - TOOL_DESCRIPTION.
# Add tool configurations here
"

if [[ "$(uname)" == "Linux" ]]; then
    if
           # if a file does not exists
           [ ! -e "$LOCAL_BASH_CONFIG_FILE" ] ||
           # if it doesn't have the content of BASH_CONFIGS
           ! grep -q -z "$BASH_CONFIGS" "$LOCAL_BASH_CONFIG_FILE"; then
        echo appending
        printf '%s\n' "$BASH_CONFIGS" >> "$LOCAL_BASH_CONFIG_FILE"
    else
        echo not appending
    fi

elif [[ "$(uname)" == "Darwin" ]]; then
    if 
            [ ! -e "$LOCAL_BASH_CONFIG_FILE" ] || 
            ! grep -q "$(<<<"$BASH_CONFIGS" tr '\n' '\01')" < <(
                less "$LOCAL_BASH_CONFIG_FILE" | tr '\n' '\01'
            ); then
        echo appending
        printf '%s\n' "$BASH_CONFIGS" >> "$LOCAL_BASH_CONFIG_FILE"
    else
       echo not appending
    fi
fi

}

关于string - 在bash中检查文件是否包含多行字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53900318/

相关文章:

javascript - 我可以使用三等号来比较 JavaScript 字符串吗?

c - C 中的 Fscanf、字符串和数组?

bash - 如何在 Bash 中查找变量是否为空

eclipse sh 编辑并运行

ios - 如何使用 bundle 中的数据移动 sqlite3 数据库

linux - 预测操作系统崩溃

regex - 更改r中字符串中单词的位置

c - 文件字符串结束符

linux - 不同文件夹中的同名文件

cocoa - 获取 Mac OS X 中的本地化文件大小