简体   繁体   中英

Add certain variables value in between characters in bash

I am currently writing one script which creates an issue in jira based on //TODO comments in my java file. for that, i am using JIRA REST API.

here's my testing script which creates only one issue from a file,

#!/bin/bash
file=jira.txt


while IFS='' read -r line || [[ -n "$line" ]]; do
filename=$(tr -d '\n\r' <<< $(cut -d':' -f1 <<< $line))
summary=$(tr -d '\n\r' <<< $(cut -c4- <<< $(cut -d':' -f3 <<< $line)))

echo -e "\033[1mIssue Name\033[0m = $summary"
echo -e "\033[1mDescription\033[0m = $filename"
key="Project-181"
#key=$(curl -u username:password -X POST --data '{
#    "fields": {
#       "project":
#       {
#          "key": "project"
#       },
#       "summary": "'"$summary"'",
#       "description": "'"$filename"'",
#       "issuetype": {
#          "name": "Task"
#       }
#   }
#}' -H "Content-Type: application/json" http://JIRA-URL/rest/api/2/issue/ | jq '.key')
echo "key=$key"
sed  -i "/${summary}/s/$/ ${key}/" $filename
    done < "$file"

OUTPUT of script is,

Issue Name = TODO remove hack for my task
Description = /opt/test/testfile.java
key=project-181

I purposely commented JIRA REST API part as I don't want to generate new issue every time I ran test script

the output of commented JIRA REST API is as same as a variable declared above that " key="Project-181 "

Content of jira.txt is as follows,

/opt/test/testfile.java:211:            // TODO remove hack for my task

Now if I ran this script it will run successfully but when I check into "testfile.java " I see this,

 // TODO remove hack for my task "Project-181"

I want something like that to happen,

// TODO project-181 Remove hack for my task 

Any suggestion would be welcome Thank You.

Given summary="TODO remove hack for my task" , if you want to insert $key after the "TODO", change the sed line to this:

sed  -i "/${summary}/s/TODO \(.*\)/TODO ${key} \1/" $filename

Your original sed command "/${summary}/s/$/ ${key}/" replaced the end of the line $ with a space followed by $key , effectively appending $key to the end instead of inserting after "TODO".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM