gpt4 book ai didi

linux - 如果字符串的一部分使用 shell 脚本匹配,则替换行

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:42:47 25 4
gpt4 key购买 nike

我有一个名为 config.txt 的文件,其中包含类似这样的内容。

[MS-SQL]
DRIVER : FreeTDS
SERVER : 138.23.21.45

我需要做的是,无论 SERVER : 之后包含的字符串值需要替换为 shell 变量中的内容,如 $SERVER_IP

最终config.ini需要这样。(考虑 bash shell 变量包含一些这样的 $SERVER_IP=192.168.5.3 )

[MS-SQL]
DRIVER : FreeTDS
SERVER : 192.168.5.3

最佳答案

这将改变行:

sed -iE 's/(SERVER : )([0-9.]+)/\1'"$SERVER_IP"'/' config.txt

描述:

-i                    # write changes to the file "in place".
-E # Use extended regex (to avoid the need
# of backslash in `()`)
's/ … / … /' # Use the substitute command.
(SERVER : ) # Match the string you need `SERVER : ` capturing it
# in the first group of parenthesis.
([0-9.]+) # capture digits and dots in the second group.
/\1'"$SERVER_IP"'/' # write the contents of the first group and
# the value of the variable to the file.
config.txt # name of the file.

如果需要,您也可以更改 DRIVER 之后的值:

sed -iE 's/(DRIVER : )(.*)/\1ODBC/' config.txt

关于linux - 如果字符串的一部分使用 shell 脚本匹配,则替换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40903929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com