zoukankan      html  css  js  c++  java
  • sed中使用变量及变量中存在特殊字符‘/’处理

    sed中使用变量,普通的处理方式无法解析变量

    如当前file文件中存在字符串pedis,现将其替换为redis

    [root@localhost work]# cat file 
    pedis

    如下两种替换方式,都是行不通的

    #!/bin/bash
    
    old_str=pedis
    new_str=redis
    
    sed -i 's/$old_str/$new_str/g' file
    sed -i 's#$old_str#$new_str#g' file

    将变量用三个单引号引起来,可以解决上述问题

    #!/bin/bash
    
    old_str=pedis
    new_str=redis
    
    #sed -i 's/$old_str/$new_str/g' file
    
    #sed -i 's#$old_str#$new_str#g' file
    
    sed -i 's/'''$old_str'''/'''$new_str'''/g' file

    执行结果

    [root@localhost work]# cat file 
    pedis
    [root@localhost work]# ./replace.sh 
    [root@localhost work]# cat file 
    redis

     当变量中存在特殊字符/,上面的替换方式就不合适了,需要将/改为#

    #!/bin/bash
    
    old_str=redis
    new_str=/data/
    
    sed -i 's#'''$old_str'''#'''$new_str'''#g' file

    执行结果

    [root@localhost work]# cat file 
    redis
    [root@localhost work]# ./replace.sh 
    [root@localhost work]# cat file 
    /data/
  • 相关阅读:
    0909 初识编译原理
    校园跳蚤市场-Sprint计划
    校园跳蚤市场
    5.2-5.3
    5.1封装
    阅读2
    汉堡包
    五章-问题
    结对子作业 四则运算 V2.0
    四则运算升级版
  • 原文地址:https://www.cnblogs.com/yang5726685/p/15740733.html
Copyright © 2011-2022 走看看