首页 > 解决方案 > 在 unix 字符串中第二次出现特定单词之前插入“,”

问题描述

我想在每次出现 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 显示的努力(在评论中)。

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

标签: jsonunixawksed

解决方案


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

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"

推荐阅读