简体   繁体   English

将具有命令替换功能的sed输出存储到变量中

[英]Store output of sed with command substitution in it into a variable

Consider a string 考虑一个字符串

Message="Hello WoRld"

I would like to substitute the upper case R by the lower case r 我想用小写r代替大写R

echo "$Message" > file.txt
NewMessage=$(sed 's/R/r/' file.txt)

works fine! 工作正常! The following would work as well 以下也可以

NewMessage=$(echo ${Message} | sed 's/R/r/')

But my first reflex was to use command substitution 但是我的第一反应是使用命令替换

NewMessage=$(sed 's/R/r/' <("$Message"))

but it does not work. 但它不起作用。 Why doesn't it work? 为什么不起作用?

your cmd-sub version was missing the leading M ? 您的CMD-SUB 版本缺少龙头M

But you want 但是你想要

NewMessage=$(sed 's/R/r/' <(echo "$Message"))

OR your shell may support 否则您的外壳可能会支持

NewMessage=$(sed 's/R/r/' <<< "$Message")

edit 编辑

and the simplest, most widely supported solution would be much simpler 最简单,得到最广泛支持的解决方案将更加简单

NewMessage=$(echo "$Message" | sed 's/R/r/') 

If you need absolute stone-age compatibility to Bourne Shell (true /bin/sh ) then you'll have to forego the nice $(..cmdSub) syntax and use back-quotes for command-substitution: 如果您需要与Bourne Shell的绝对石器时代兼容性(true /bin/sh ),则必须放弃漂亮的$(..cmdSub)语法,并使用反引号代替命令:

NewMessage=`echo "$Message" | sed 's/R/r/'` 

IHTH 高温超导

如果您使用的是bash 4,则不需要sed

NewMessage=${Message,,R}

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

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