英文:
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"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论