跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • shell 怎么将变量中的特殊字符替换掉
未分類
29 10 月 2020

shell 怎么将变量中的特殊字符替换掉

shell 怎么将变量中的特殊字符替换掉

資深大佬 : awanganddong 6

用 shell 脚本写一个日志的监控脚本给钉钉

变量里边的一些特殊字符需要替换掉。比如单引号,双引号,大括号等

按照$(var/被替换字符 /替换字符) 一直不成功

所以想要个 demo

另外感觉用 shell 写比 python 写麻烦的多

大家觉得呢

大佬有話說 (16)

  • 資深大佬 : weixiangzhe

    sed awk 了解一下,大部分有 shell 的环境都有 python 吧,那就改成 python 呗

  • 資深大佬 : codehz

    你括号错了

  • 資深大佬 : webshe11

    麻烦的话还是改 Python 好使,易读又严谨

  • 資深大佬 : ai277014717

    很难找到能覆盖 100%case 的 printf 试试吧

  • 資深大佬 : ai277014717

    我试过用 ruby 来做
    `printf ‘%sn’ “$VAR” | ruby -e “require ‘json’; puts JSON.dump(ARGF.read)” | tr -d ‘n’`

  • 資深大佬 : codehz

    特殊符号用斜杠转义,其他的不变
    ${var/’/2333}

  • 主 資深大佬 : awanganddong

    这是我写的
    将变量 messageStr 变量里边的单引号和双引号转化为 0
    然而失败了

    ${messageStr/'”/0}

    蛋蛋忧伤

  • 資深大佬 : jfcherng

    https://tldp.org/LDP/abs/html/parameter-substitution.html

    ${var/Pattern/Replacement}
    First match of Pattern, within var replaced with Replacement.

    If Replacement is omitted, then the first match of Pattern is replaced by nothing, that is, deleted.

    ${var//Pattern/Replacement}
    Global replacement. All matches of Pattern, within var replaced with Replacement.

    As above, if Replacement is omitted, then all occurrences of Pattern are replaced by nothing, that is, deleted.

  • 資深大佬 : somalia

    我之前也要替换成 ‘*’ ,放弃 shell 用了 python

  • 資深大佬 : misaka19000

    换 Python 写

  • 主 資深大佬 : awanganddong

    @jfcherng 看了文档,特殊字符还是没转化为 a

    “`
    myDate=`date “+%Y-%m-%d %R”`
    message=`less ‘laravel.log’|grep ‘local.ERROR’|grep “${myDate}”`
    messageStr=””
    for line in $message
    do
    messageStr=”$messageStr$line”
    done
    if [ $messageStr ];then
    messageStr=${messageStr//'”/a}
    echo $messageStr;
    curl ‘https://oapi.dingtalk.com/robot/send?access_token=token’
    -H “Content-type: application/json”
    -X POST
    -d ‘{“msgtype”: “text”,”text”: {“content”: “‘$messageStr'”},”isAtAll”: true}’
    fi

    “`

  • 資深大佬 : jfcherng

    因為你根本用錯啊… Pattern 不是 char list…

    [[email protected] Desktop]$ src=”x'”y”
    [[email protected] Desktop]$ echo ${src//[‘”]/a}
    xaay

  • 主 資深大佬 : awanganddong

    @jfcherng 感谢感谢

    另外提个问题,[] 这个不太懂,我看文档上边也没体现

  • 資深大佬 : jfcherng

    就只是一般的 regex

    看到 pattern 通常不是 regex 就是能只能頂多用 wildcard (*)

  • 主 資深大佬 : awanganddong

    技术扎实,属于大牛级别。

  • 資深大佬 : jfcherng

    @awanganddong #15 謝謝你 今晚可以開心入眠了, 不過 regex 是很常見的東西 🙂

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具