Skip to content

MacOS中shell的sed命令使用注意点 #5

Description

@allenGKC

image

背景

之前做了个在线的分享平台,但是使用的过程有些繁琐,故想起使用shell脚本将整个过程进行自动化,因为是第一次写shell脚本,所以在做的过程中遇到了一些问题,并且这些问题只是在MacOS下才有,shell脚本原生的Linux环境并没有这么多问题,如果有同学在Mac下写shell脚本遇到了和我同样的问题,可以参考一下。

问题一:-i参数的问题

问题描述:sed编辑命令:sed -i 's/a/b/g' test.txt
报错:sed: 1: "test.txt": undefined label 'est.txt'
解决方案:sed -i '' 's/a/b/g' test.txt-i后面加上一对''
原因:-i参数是强制替换原有文件,但是mac强制要求备份,否则报错,这个在Mac上系统会有问题,否则-i参数无法使用,请注意。

问题二:匹配a追加内容问题

问题描述:sed追加命令:sed -i '' "/a/a\xxx" test.txt匹配到a字符后追加xxx内容
报错:sed: 1: "/a/a\xxx": extra characters after \ at the end of a command
解决方案:在追加内容前换行,且要用双斜杠\

sed -i '' "/a/a\\
xxx \\
" test.txt

备注:/i操作同理

参考文献

  1. mac 下sed命令的-i参数
  2. mac上执行sed的编辑 -i命令报错sed

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions