Linux 在bash中将字符插入字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12230762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:14:14  来源:igfitidea点击:

Insert characters Into a string in bash?

linuxbash

提问by Andrew Mcdonald

I need to turn the string "125959"into "12:59:59".

我需要把字符串"125959"变成"12:59:59".

Obviously, the string is the time so regular expressions aren't much good here.

显然,字符串是时间,所以正则表达式在这里不太好。

采纳答案by Ansgar Wiechers

time=125959
echo ${time:0:2}:${time:2:2}:${time:4:2}

回答by Chen Levy

I like sed:

我喜欢sed

time=125959
sed -e "s/\(..\)\(..\)\(..\)/::/" <<< "$time"
  • You can refine this by replacing .with [[:digit:]]
  • Read about <<<(Here strings) in man bash(1)
  • 您可以通过替换.[[:digit:]]
  • 阅读<<<此处字符串)在man bash(1)