How to use variables in sed Unix utility

Often,  sed will be used in your Makefile.

It will be very convenient if we can use variables in sed.
There is a very simple way, but a lot of work has been done before I find that.


Here is an example:

Let's assume you want to cut the suffix ".img" of a file name, abc.img.

The result should be "abc" after running sed command to "abc.img".

In normal without variables,  it may go like this  

              echo -nE abc.img | sed 's/.img//'

Let's run it as below:

[xbai]$ echo -nE abc.img |
>  sed 's/.img//'
abc[xbai]$

or,

[xbai]$ echo -nE abc.img | sed 's/.img//'
abc[xbai]$

 

Yeah, you may see the  abc in bold. There is no line-feed, '\n'.  This is done with option "-nE" in echo command.

 

But, what if we use a variable for that file name.

FILE = abc.img

SUFFIX = .img

what is the sed command to reach the same goal?

It is

echo -nE $(FILE) | sed 's/'${SUFFIX}'//'

This command will meet your requirement if you have the same need.

the key point is  referencing variables in sed

'$(SUFFIX)'  or '${SUFFIX}'

 

That is all here.

Thanks.

posted on 2012-09-13 10:34  Shawn X.Y. Bai  阅读(239)  评论(1)    收藏  举报

导航