sed用变量中的文本替换文本

时间:2017-07-14 22:20:25

标签: linux bash sed scripting

我们有如下的ASCII艺术

ART  _____                            
ART |  __ \               
ART | |__) |__  ___ _ __   
ART |  ___/ _ \/ _ \ '__|  
ART | |  |  __/  __/ |    
ART |_|   \___|\___|_|     
ART                        
ART                        

我们有一个变量$ {art} =" 123456"并希望用$ {art}替换ART,因此系统将打印标准输出,如此

123456  _____                            
123456 |  __ \               
123456 | |__) |__  ___ _ __   
123456 |  ___/ _ \/ _ \ '__|  
123456 | |  |  __/  __/ |    
123456 |_|   \___|\___|_|     
123456                        
123456                       

我试过这个,因为这篇文章建议

sed -i "s/ART/${art}/g" ascii-art 

显示以下错误消息:

sed: -e expression #1, char 6: unterminated `s' command

我在Linux ip-10-22-37-149 4.4.8-20.46.amzn1.x86_64 #1 SMP Wed Apr 27 19:28:52 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux (Amazon EC2)

sed --version返回:

GNU sed version 4.2.1
Copyright (C) 2009 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE,
to the extent permitted by law.

GNU sed home page: <http://www.gnu.org/software/sed/>.
General help using GNU software: <http://www.gnu.org/gethelp/>.
E-mail bug reports to: <bug-gnu-utils@gnu.org>.
Be sure to include the word ``sed'' somewhere in the ``Subject:'' field.

有什么想法?

谢谢!

1 个答案:

答案 0 :(得分:1)

如果$art包含/,您可能需要反斜杠或使用其他分隔符。

或者,使用Perl:

perl -i -pe 's/ART/$ENV{art}/g' -- file

这将在导出$art时起作用,如果不导出,只需将其导出为命令:

art=$art perl ...