使用sed或awk或全新Debian 9安装中的工具,如何不加修饰地附加文本? [英] Using sed or awk or a tool from a fresh Debian 9 install, how to do text appending untrimmed?

查看:146
本文介绍了使用sed或awk或全新Debian 9安装中的工具,如何不加修饰地附加文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用sed或awk或全新debian 9中存在的工具进行安装,请执行以下文本附加操作:

How can I with sed or awk or a tool present in fresh debian 9 install, do the following text appending:

sed '/"start":/a     "start:prod": "hello",' package.json

当前我的字符串起始空格已修剪

Currently my string starting spaces are trimmed

这就是我们拥有的:

  "scripts": {
    "start": "export REACT_APP_ENV=${REACT_APP_ENV:-default} && cp src/env/.env.$REACT_APP_ENV .env && react-scripts start",

"start:prod":"hello", ... }

"start:prod": "hello", ... },

这是我们期望的:

  "scripts": {
    "start": "export REACT_APP_ENV=${REACT_APP_ENV:-default} && cp src/env/.env.$REACT_APP_ENV .env && react-scripts start",
    "start:prod": "hello",
    ...
  },

推荐答案

只需在a命令后添加\(假定来自linux标签的GNU sed)

Just add \ after a command (assuming GNU sed from linux tag)

$ seq 3 | sed '/2/a foobaz'
1
2
foobaz
3
$ seq 3 | sed '/2/a\ foobaz'
1
2
 foobaz
3

来自 GNU sed手册

a命令后的空白行将被忽略

Leading whitespace after the a command is ignored

文本中的转义序列已处理,因此您应在文本中使用\\来打印单个反斜杠

Escape sequences in text are processed, so you should use \\ in text to print a single backslash


另一种方法是使用r命令


Alternate way is to use r command

$ seq 3 > ip.txt
$ # need to take care of escape sequences, unless that is a feature you need
$ sed '/2/a\ a\\ny' ip.txt
1
2
 a\ny
3

$ # r command will add the text as is
$ # won't cause trouble for multiline text, clashes with sed meta characters, etc
$ echo ' a\ny' | sed '/2/r /dev/stdin' ip.txt
1
2
 a\ny
3
$ # or from file input
$ echo ' a\ny' > f1
$ sed '/2/r f1' ip.txt
1
2
 a\ny
3

或者,使用替代命令在行首捕获空白并重复用于追加

or, use the substitute command to capture blanks at start of line and reuse for appending

$ echo '  hello123' | sed -E 's/^([[:blank:]]+)hello.*/&\n\1hi/'
  hello123
  hi

这篇关于使用sed或awk或全新Debian 9安装中的工具,如何不加修饰地附加文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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