Thursday, February 3, 2022

[SOLVED] insert ", " before 2nd occurrence of a particular word in string in unix

Issue

I want to insert ", " before every occurrence of a https, except first https in the below JSON

input:

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

Output:

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

EDIT: Adding OP's shown efforts(in comments) in post here.

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

Solution

Could you please try following (written and tested with provided samples).

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

Explanation: Adding a detailed level of explanation for above code.

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.

To save output into shell variable and read values from shell variable try like (where var is your shell variable having values, you could name it as per your wish):

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


Answered By - RavinderSingh13
Answer Checked By - Robin (WPSolving Admin)