简体   繁体   English

bash脚本替换字符串中的值

[英]bash script to replace values in a string

I've used awk and grep in the past to extract substrings using a bash script, but what I can't figure out is how to find a substring and then replace part of a value in that substring using a bash script.我过去曾使用 awk 和 grep 使用 bash 脚本提取子字符串,但我不知道如何找到子字符串,然后使用 bash 脚本替换该子字符串中的部分值。

If I have a string as follows:如果我有一个字符串如下:

"key val1=0 val2=15 val3=22 'some notes here'"

How can I efficiently update val1, val2, and val3 values to something else?如何有效地将 val1、val2 和 val3 值更新为其他值? So if I wanted to change "val1=0" to "val1=9999", and "val2=22" to "val2=0".因此,如果我想将“val1=0”更改为“val1=9999”,将“val2=22”更改为“val2=0”。

I could split the string based on spaces, loop through the values to find val1, split it to get 0, change 0 to 9999(repeat for val2), but then how do I recreate the original string with the original values so I wind up with:我可以根据空格拆分字符串,遍历值以找到 val1,将其拆分为 0,将 0 更改为 9999(对 val2 重复),但是如何使用原始值重新创建原始字符串,这样我就结束了和:

"key val1=9999 val2=0 val3=22 'some notes here'"

I have a requirement that this gets done in a bash script, which I am not very familiar with, so switching it over to python, perl, or some other language isn't an option for me unfortunately.我有一个要求,这要在我不太熟悉的 bash 脚本中完成,因此不幸的是,将其切换到 python、perl 或其他一些语言对我来说不是一个选择。

The strings would be passed to the script via STDIN if that makes a difference.如果这有所不同,这些字符串将通过 STDIN 传递给脚本。 The only pieces of the string I am interested in changing is "val#=#", all other text should remain untouched.我唯一有兴趣更改的字符串是“val#=#”,所有其他文本都应保持不变。

Using pure bash使用纯 bash

Let's start with your string:让我们从你的字符串开始:

$ s="key val1=0 val2=15 val3=22 'some notes here'"

Now, let's replace, as an example, val1 :现在,让我们替换val1为例:

$ s="${s/val1=0/val1=9999}"
$ echo "$s"
key val1=9999 val2=15 val3=22 'some notes here'

The construct ${var/old/new} is called pattern substitution .构造${var/old/new}称为模式替换 The value of old can be a character simple string or a shell glob. old的值可以是一个简单的字符字符串或一个 shell glob。

Using bash and sed使用 bash 和 sed

In bash scripts, sed is often used for string manipulation and it works well with stdin.在 bash 脚本中, sed通常用于字符串操作,并且它与 stdin 配合得很好。 For example, to perform two substitutions at once:例如,要一次执行两个替换:

$ input="key val1=0 val2=15 val3=22 'some notes here'"
$ echo "$input" | sed 's/val1=[^ ]*/val1=9999/; s/val2=[^ ]*/val2=0/'
key val1=9999 val2=0 val3=22 'some notes here'

The output of sed can, of course, be captured in a shell variable using command substitution :当然,可以使用命令替换将 sed 的输出捕获到 shell 变量中:

$ new="$(echo "$input" | sed 's/val1=[^ ]*/val1=9999/; s/val2=[^ ]*/val2=0/')"
$ echo "$new"
key val1=9999 val2=0 val3=22 'some notes here'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM