【问题标题】:shell: how to replace a string with a new string containing a spaceshell:如何用包含空格的新字符串替换字符串
【发布时间】:2021-11-23 09:24:07
【问题描述】:

我有一个txt文件,内容如下:

hello my name 
is teddy bear, 
I like 
eating sweet honey!

我想将行 is teddy bear 替换为 is sleepy bear,用 shell 脚本。

我正在尝试以下代码:

#!/bin/sh

ORI_LINE="is[[:space:]]teddy[[:space:]]bear"
NEW_LINE="is[[:space:]]sleepy[[:space:]]bear"

eval sed -i -e 's/$ORI_LINE/$NEW_LINE/g' ./hello.txt

但最后我得到了

hello my name 
is[[:space:]]sleepy[[:space:]]bear, 
I like 
eating sweet honey!

其中[[:space:]] 未解析为真实空间。

我想继续使用变量 ORI_LINENEW_LINE,而不是使用 sed 命令的内联字符串。

谢谢!

【问题讨论】:

标签: bash shell sed


【解决方案1】:

好吧,你告诉它把那个模式放进去。替换字符串应该有实际的空格,而不是可以匹配各种类型的“空格”字符的正则表达式模式。

如果

$: txt="hello my name is teddy bear,
I like eating sweet honey!"
$: ORI_LINE="is[[:space:]]teddy[[:space:]]bear"
$: NEW_LINE="is sleepy bear"

然后

$: sed "s/$ORI_LINE/$NEW_LINE/g" <<< "$txt"
hello my name is sleepy bear,
I like eating sweet honey!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-25
    • 2017-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    相关资源
    最近更新 更多