Sed正则表达式字符串替换

huangapple go评论49阅读模式
英文:

Sed Regex String Replacement

问题

以下是翻译好的部分:

# to convert duration-based timeouts to 30s
sed -i 's/"{{.*timeout.*[0-9]+s."/"30s"/' $DIR/config.txt

# to convert non-duration-based timeouts to 3000
sed -i 's/"{{.*timeout.*[0-9]+.}}"/"3000"/' $DIR/config.txt
英文:

I am trying to replace lines containing the word timeout with a specific value using sed. See the example below. Can someone point me to what I am doing wrong here?

There are two types of timeouts, one that is declared as a duration (i.e. with s or m appended ) and one without.

Content in text ($DIR/config.txt) :

timeout="{{key_or_default "/config/timeout" "2s"}}"          # declared as a duration
interval="{{key_or_default "/config/fetchInterval" "5m"}}"
another_timeout="{{key_or_default "/config/timeout" "2"}}"   # declared not as a duration
yet_another_timeout_ms="{{key_or_default "/config/timeout" "2"}}"

Expected outcome

timeout="30s"          # declared as a duration
interval="{{key_or_default "/config/fetchInterval" "5m"}}" # no change needed as it does not have the word timeout
another_timeout="3000"   # declared not as a duration
yet_another_timeout_ms="3000"

sed commands which I tried are below,

# to convert duration-based timeouts to 30s
sed -i 's/"{{.*timeout.*[0-9]+s."/"30s"/' $DIR/config.txt

# to convert non-duration-based timeouts to 3000
sed -i 's/"{{.*timeout.*[0-9]+.}}"/"3000"/' $DIR/config.txt

答案1

得分: 1

With duration based:

sed -E -i 's/([a-z_]*timeout\w*=)[^0-9]*([0-9]+[a-z]+)[^0-9]+/\1"30s"/g' $DIR/config.txt

Without duration based:

sed -E -i 's/([a-z_]*timeout\w*=)[^0-9]*([0-9]+")[^0-9]+/\1"3000"/g' $DIR/config.txt

Output:

timeout="30s"
interval="{{key_or_default "/config/fetchInterval" "5m"}}"
another_timeout="3000"
yet_another_timeout_ms="3000"
英文:

With duration based:

sed -E -i 's/([a-z_]*timeout\w*=)[^0-9]*([0-9]+[a-z]+)[^0-9]+/\1"30s"/g' $DIR/config.txt

Without duration based:

sed -E -i 's/([a-z_]*timeout\w*=)[^0-9]*([0-9]+")[^0-9]+/\1"3000"/g' $DIR/config.txt

Output:

timeout="30s"
interval="{{key_or_default "/config/fetchInterval" "5m"}}"
another_timeout="3000"
yet_another_timeout_ms="3000"

答案2

得分: 0

使用 sed

$ sed -Ei.bak 's/\{+[^}]*timeout" "[0-9]+([a-z]*)"}/3000/' input_file
timeout="3000s"
interval="{{key_or_default "/config/fetchInterval" "5m"}}"
another_timeout="3000"
英文:

Using sed

$ sed -Ei.bak 's/\{+[^}]*timeout" "[0-9]+([a-z]*)"}+/3000/' input_file
timeout="3000s"
interval="{{key_or_default "/config/fetchInterval" "5m"}}"
another_timeout="3000"

huangapple
  • 本文由 发表于 2023年2月19日 11:39:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75497837.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定