【问题标题】:insert ", " before 2nd occurrence of a particular word in string in unix [closed]在unix中字符串中第二次出现特定单词之前插入“,” [关闭]
【发布时间】:2020-05-15 15:40:16
【问题描述】:

我想在每次出现 https 之前插入 "、",但下面 JSON 中的第一个 https 除外

输入:

https://gitlab.com/pc-sa/sa-pc-pcc/-/archive/test-demo/abc-test-demo.zip?path=Documentation Assets/temp check
https://gitlab.com/pc-sa/sa-pc-pcc/-/archive/test-demo/abc-test-demo.zip?path=Documentation Assets/temp dir
https://gitlab.com/pc-sa/sa-pc-pcc/-/archive/test-demo/abc-test-demo.zip?path=Documentation Assets/temp dir

输出:

https://gitlab.com/pc-sa/sa-pc-pcc/-/archive/test-demo/abc-test-demo.zip?path=Documentation Assets/temp check", "https://gitlab.com/pc-sa/sa-pc-pcc/-/archive/test-demo/abc-test-demo.zip?path=Documentation Assets/temp dir", "https://gitlab.com/pc-sa/sa-pc-pcc/-/archive/test-demo/abc-test-demo.zip?path=Documentation Assets/temp dir

编辑:在此处的帖子中添加 OP 显示的努力(以 cmets 为单位)。

cat /tmp/mmm.txt| sed ':a;N;$!ba; s/https/\","https/2'

【问题讨论】:

  • 这不清楚,请在您的帖子中添加更多清晰的细节,然后让我们知道。
  • 你在 sed 中尝试过什么吗?
  • 猫 /tmp/mmm.txt| sed ':a;N;$!ba; s/https/\","https/2' 但我不知道还有多少个 https 字符串,我想忽略第一个 https 字符串,对于剩余的第 n 个 https 它应该附加 ",".
  • 包含什么字符串?是文件吗?某些命令的标准输出?还有什么?请在问题本身中向我们展示您的代码。
  • @14MAR,您已更改示例,这些示例未显示您之前显示的示例,这将是完全不同的问题本身。因此,请自行放置以前的示例并为这些示例打开一个新问题。

标签: json unix awk sed


【解决方案1】:
 awk 'BEGIN{ORS=','}1' file

这会在最后给你一个额外的逗号

 awk '{printf (FNR==1?"":",")"%s", $0}' file

这不会

【讨论】:

    【解决方案2】:

    您能否尝试以下操作(使用提供的示例编写和测试)。

    awk -v s1="\",\"" '{val=(val?val s1:"")$0} END{print val}'  Input_file
    

    说明:为上述代码添加详细级别的说明。

    awk -v s1="\",\"" '         ##Starting awk program here and creating variable s1 whose value is ","
    {                           ##Starting this code main BLOCK from here.
      val=(val?val s1:"")$0     ##Creating variable val whose value is keep concatenating to its own value.
    }                           ##Closing this program main BLOCK here.
    END{                        ##Starting END block of this program from here.
      print val                 ##Printing variable val here.
    }                           ##Closing this program END block here.
    '  Input_file               ##Mentioning Input_file name here.
    

    要将输出保存到 shell 变量中并从 shell 变量中读取值,请尝试如下(var 是您的 shell 变量有值,您可以根据自己的意愿命名):

    var=$(echo "$var" | awk -v s1="\",\"" '{val=(val?val s1:"")$0} END{print val}'); echo "$var"
    

    【讨论】:

      【解决方案3】:

      我会更改所有个出现,然后将第一个改回:

      sed -e 's/https/", "https/g' -e 's/", "https/https/'
      

      (您的示例与您对目标的描述不太匹配,因此我无法测试此解决方案,但我认为它至少大致正确。)

      【讨论】:

      • 这也会添加第一个 https,我不想这样做。我想首先排除 https ,其余的应该附加“,”。
      猜你喜欢
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-07
      • 1970-01-01
      • 2021-09-11
      • 2021-10-26
      相关资源
      最近更新 更多