sed 对变量而不是标准输入或文件进行操作 [英] Have sed operate on variable instead of standard input or a file

查看:44
本文介绍了sed 对变量而不是标准输入或文件进行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多问题询问如何在sed模式中使用变量,例如:sed "s/re/$VAR/" file,但我想执行替换on 一个变量.到目前为止,我一直在使用 echo 来做到这一点:

There are many questions asking about how to use a variable within a sed pattern, for example: sed "s/re/$VAR/" file, but I want to perform a substitution on a variable. So far, I have been using echo to do this:

echo "$VAR" | sed 's/re/new/'

但是,虽然这有效,但看起来很混乱.在 bash 或 zsh 中是否有更简单/更优雅的方法?

But, though this works, it seems messy. Is there a simpler/more elegant way of doing this in bash or zsh?

推荐答案

你可以这样做:

sed 's/re/new' <<< "$var"

如果你想这样做并更新变量,你可以这样做:

If you want to do that and update the variable you can do this:

var=$(sed 's/re/new' <<< "$var")

这篇关于sed 对变量而不是标准输入或文件进行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆