Shell:在替换模式时忽略转义序列 [英] Shell: Ignore escape sequences while replacing a pattern

查看:45
本文介绍了Shell:在替换模式时忽略转义序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了这个主题并看到了一些示例,但不知何故它对我不起作用.我必须在 shell 脚本(包含文件路径和扩展名)中的文件中用另一行替换一行.我正在使用以下命令,但替换不起作用.

I have searched this topic and saw some examples but somehow it doesnt work for me. i have to replace one line with another in a file in shell script (which contains file path and extension). I am using below command but replace is not working.

line='a|b|c|\\folder\file.txt'
upd_line='a|b|c|\\folder\file.txt|d'
sed -i 's#$line#$upd_line#g' sample.txt

sample.txt 内容:

sample.txt content:

HDR|date

a|b|c|\\folder\file.txt

我希望用 $upd_line 的内容替换第二行,但它保持不变.请告知我做错了什么.我在 bash 和 ksh 中尝试过,但没有运气.

I am expecting second line to be replaced with content of $upd_line but it remains unchanged. Please advise what am i doing wrong. i tried in bash and ksh with no luck.

推荐答案

这可能对你有用(GNU sed & bash):

This might work for you (GNU sed & bash):

a='a|b|c|\\folder\file.txt'
b='a|b|c|\folder\file.txt|d'

qs(){ sed <<<$1 's/[][\\.*^$]/\\&/g';}

sed "s/$(qs $a)/$(qs $b)/" file

这将创建一个函数 qs,它将变量字符串转换为 sed 正则表达式和替换中可接受的形式.

This creates a function qs which converts the variable strings to the accepted form in the sed regexp and replacement.

注意在 sed 命令周围使用双引号;这允许 shell 插入 shell 变量和函数调用.如果在您选择的终端中使用了 GNU readline,C-M-e 将在 shell 运行 sed 命令之前向您显示插值的结果(您可能需要在真正运行它们之前重新引用结果).

N.B. the use of double quotes around the sed command; this allows the shell to interpolate the shell variables and function calls. If GNU readline is used in your choice of terminal, C-M-e will show you the results of the interpolation before the shell runs the sed command (you may need to requote the results before running them for real).

这篇关于Shell:在替换模式时忽略转义序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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