简体   繁体   中英

Issue with bash script using SED/AWK for substituion

I have been working on this little script at work to free up my own time and am currently stuck on part of it. The script is supposed to pull some content from a JSON, modify the content, and then re-upload it. The modification part is the portion that doesn't work.

An example of what the content looks like after being extracted from the JSON is:

<p>App1_v1.0_20160911_release.apk</p<p>App2_v2.0_20160915_beta.apk</p><p>App3_v3.0_20150909_VendorRelease.apk</p>

The modification function is supposed to update the list with the newer app filenames in the same location. I've tried using both SED and AWK to get this to work but I haven't gotten anywhere fast.

Here are examples of both commands and the parameters for the substitution I am trying to run on the example file:

old_name=App1_.*_release.apk
new_name=App1_v1.0_20160920_1152_release.apk

sed "s/$old_name/$new_name/" body > upload

awk -v oldname="$old_name" -v newname="$new_name" '{sub(oldname, newname)}1' body > upload

What ends up happening is the substitution will change the correct part of the list, but then nuke everything between that point and the end of the list.

Thank you for any and all help.

PS: If I didn't explain something correctly or you feel some information is missing, please comment and let me know so I can better explain the problem.

There are SO many possible values of oldname, newname, and your input data that could cause either of the commands you wrote to fail - don't use that "replace a regexp with a backreference-enabled-string" approach in any command, use string operations instead (which means you can't use sed since sed doesn't support strings)

This modifies your sample input as you say you want:

$ awk -v new='App1_v1.0_20160920_1152_release.apk' 'BEGIN{RS="</p>\n?"; FS=OFS="<p>"} NR==1{$2=new} {printf "%s%s", $0, RT}' file
<p>App1_v1.0_20160920_1152_release.apk<p>App2_v2.0_20160915_beta.apk</p><p>App3_v3.0_20150909_VendorRelease.apk</p>

If that's not adequate then edit your question to better explain your requirements and provide more truly representative sample input/output.

The above uses GNU awk for multi-char RS and RT.

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