如果 Bash 中的文件中不存在值,则在一行中搜索并替换或附加值(适用于 Linux 和 MacOS)

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

我有一个这样的文件:

one_variable=/tmp
version=16.0
another_variable=jack

并且我正在尝试搜索并替换

version
的值(如果存在)或附加
version=newvalue
(如果不存在)。

目前我正在使用这个单行 sed 命令,它在 Linux 上运行得很好。它将

version
的值替换为
$version_selected
或将新值附加到
version=

# sed -i'' -e "/^version=/{h;s/=.*/=$version_selected/};\${x;/^$/{s//version=$version_selected/;H};x}" infile

但是,在 MacOS 上这会引发错误:

sed: 1: "/^version=/{h;s/=. ...": bad flag in substitute command: '}'

如何让它在一行中同时在 Linux 和 MacOS 上运行?也许

awk
可以毫无问题地做同样的事情吗?或者是其他东西?我不工作使用
gsed

linux bash sed
1个回答
0
投票

使用我正在演示的这个小bash脚本..使用通配符替换整行

.*
然后将其替换为
version=$version_selected

版本.txt

one_variable=/tmp
version=16.0
another_variable=jack

版本.sh

#!/bin/bash -e

file=version.txt
version_selected=17.56

sed -i "s/version.*/version=$version_selected/g" "$file"

您在version.txt中替换的内容应该是:

one_variable=/tmp
version=17.56
another_variable=jack
© www.soinside.com 2019 - 2024. All rights reserved.