首页 > 解决方案 > Bash - 从特定字符串开始删除文件的全部内容

问题描述

我在 yml 文件中有一个字符串,其中包含:# base config。现在我想从这个特定的字符串开始从这个文件中删除所有内容。我也想删除这个字符串。有命令吗?

.bash 文件

for filename in ./config/*.yml; do
    if grep -qxF "# base config" $filename
    then
        echo "has base config, will replace it"
        sed -i "" "# base config/q" $filename # this does not do anything
    else
        echo "has NOT base config, will add it"
        cat $base_config >> $filename
    fi
done

标签: bashmacossed

解决方案


使用 sed:

sed -n '/#base config/q;p' file

或者使用 awk:

awk '/#base config/{exit};1' file

因此,您可以将脚本中的 sed 行替换为以下两个:

sed -n '/#base config/q;p' "$filename" > tmpfile
mv tmpfile "$filename"

请注意,我双引号引用了变量,这是一个很好的做法。


推荐阅读