Replace JSON key using SED - json

I am trying to get a JSON key and change its property in the file using -i flag with sed. The issue is, I cannot get this regex right. It works perfectly fine for the simple replace case, but I cannot get it working using this regex. For simplicity, I have just tried a simple echo, rather than saving it to the file. Ideas?
x=0.0.179
echo "version: 0.0.178" | sed 's/^[ ]*\"version\"[ ]*:[ ]*\"\([0-9]+\.[0-9]+\.[0-9]+\)\".*$/\$x/'
0.0.178

Why should you be complicating it with sed, just do,
x="0.0.179"
echo "version: 0.0.178" | sed "s/version: .*/version: $x/"
version: 0.0.179
and BTW if your JSON input can be parsed and modified via jq, go for it. Use this ONLY as a last resort.

I think your sed regexp is looking for the version number within double-quotes. Your input to sed above is not quoted as such, and hence doesn't get replaced (I'd expect your JSON to be double-quoted though, hence my interest above re. your real JSON input).

This works. Mention the 's around $x
echo "version: 0.0.178" | sed 's/^[ ]*\"version\"[ ]*:[ ]*\"\([0-9]+\.[0-9]+\.[0-9]+\)\".*$/\'$x'/'
Bash variables do not get replaced inside strings with '. Use " whenever possible to avoid this, or just concat your variable into the command as shown above.

Related

Finding and replacing last segment of ip addresses with sed

I have bunch of json files that contains web events. Each event contains lots of stuff and I'm trying to do ip address anonymization (replacing last segment of ip addresses with 0) with sed.
In short:
How to find substrings like "ip":"34.542.3.34" from json files and transform them to "ip":"34.542.3.0"?
Attempts:
Resetting starting point with \K
sed -e 's/"ip":"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.\K[0-9]{1,3}/0/g' file.json
This would work but unfortunately sed doesn't seem support reseting starting point.
Negative lookbehind
sed -e 's/(?<="ip":"[0-9]{3}\.[0-9]{3}\.[0-9]{3}\.)([0-9]{3})/0/g' file.json
This would also work but negative lookbehind doesn't seem to support non-fixed-width assortions. So [0-9]{1,3} is not supported and hence this won't work.
Matching groups
Third idea was to use matching groups and do something like this
sed -e 's/("ip":"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|([0-9]{1,3})/\1\20/g' file.json
But couldn't figure out how this would actually work with sed.
Writing regex for every possible length option separately
This would probably work but it would make regex too long and hardly readable. I would like to find more convenient and clean solution.
Any suggestions?
With GNU sed:
sed -r 's/("ip":"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)[0-9]{1,3}(")/\10\2/' file
When there's no -r-option:
sed -e 's/\("ip":"[[:digit:]]\{1,3\}\(\.[[:digit:]]\{1,3\}\)\{2\}\.\)\([[:digit:]]\{1,3\}\)"/\10"/g' tst.json

using sed in script to add html tag to text

I'm trying to use sed in a shell script to add html hyperlink tags to a url in a plain text file.
This is the content of my newtext.txt:
www.example.com
And here is the desired content of newtext.txt that I would like after running my script:
www.example.com
Here is the content of my current script, addhtml.sh:
#!/bin/bash
newtextv='cat newtext.txt'
sed -i.bak 's|\(www.*\)|\1|' newtext.txt
But unfortunately, after running the script, the content of newtext.txt becomes:
www.example.com
I believe my error somehow relates to how my variable is being quoted?
I eventually want this script to also be able to convert full urls (containing http:// )... I obviously need to improve my sed knowledge a good deal (it's taken me a few days to get this far), but I can't wrap my head around this one.
Thank you!
If you want to put the file's content into a variable:
newtextv=$(cat newtext.txt)
But really, you probably want something like this (but with a better regex, obviously):
sed 's|www\.[^ ]*|&|g' <newtext.txt >newtext.html
Sed replaces every & with the matched string.
Why mess around with a variable?
sed -i 's|\(www.*\)|\1|' newtext.txt
or
sed -i 's|www.*|&|' newtext.txt
If you happen to have the URL in a variable you can also do it without sed:
newtextv=www.example.com
echo "$newtextv"
returns
www.example.com
In Bash you can manipulate variables as a subset of variable substitution.
Here ${newtextv#www.} basically means take $newtextv and cut "www." from its beginning
Your trouble is two little syntax errors:
cat newtext.txt will never execute, you need to use backquotes ` or $()
using single quotes ' prevents variables from expanding. To allow variable expansion use double quotes "
here is what you want to do:
#!/bin/bash
newtextv=$(cat newtext.txt)
sed -i.bak "s|\(www.*\)|\1|" newtext.txt

Replacing HTML tag content using sed

I'm trying to replace the content of some HTML tags in an HTML page using sed in a bash script. For some reason I'm not getting the proper result as it's not replacing anything. It has to be something very simple/stupid im overlooking, anyone care to help me out?
HTML to search/replace in:
Unlocked <span id="unlockedCount"></span>/<span id="totalCount"></span> achievements for <span id="totalPoints"></span> points.
sed command used:
cat index.html | sed -i -e "s/\<span id\=\"unlockedCount\"\>([0-9]\{0,\})\<\/span\>/${unlockedCount}/g" index.html
The point of this is to parse the HTML page and update the figures according to some external data. For a first run, the contents of the tags will be empty, after that they will be filled.
EDIT:
I ended up using a combination of the answers which resulted in the following code:
sed -i -e 's|<span id="unlockedCount">\([0-9]\{0,\}\)</span>|<span id="unlockedCount">'"${unlockedCount}"'</span>|g' index.html
Many thanks to #Sorpigal, #tripleee, #classic for the help!
Try this:
sed -i -e "s/\(<span id=\"unlockedCount\">\)\(<\/span>\)/\1${unlockedCount}\2/g" index.html
What you say you want to do is not what you're telling sed to do.
You want to insert a number into a tag or replace it if present. What you're trying to tell sed to do is to replace a span tag and its contents, if any or a number, with the value of in a shell variable.
You're also employing a lot of complex, annoying and erorr-prone escape sequences which are just not necessary.
Here's what you want:
sed -r -i -e 's|<span id="unlockedCount">([0-9]{0,})</span>|<span id="unlockedCount">'"${unlockedCount}"'</span>|g' index.html
Note the differences:
Added -r to turn on extended expressions without which your capture pattern would not work.
Used | instead of / as the delimiter for the substitution so that escaping / would not be necessary.
Single-quoted the sed expression so that escaping things inside it from the shell would not be necessary.
Included the matched span tag in the replacement section so that it would not get deleted.
In order to expand the unlockedCount variable, closed the single-quoted expression, then later re-opened it.
Omitted cat | which was useless here.
I also used double quotes around the shell variable expansion, because this is good practice but if it contains no spaces this is not really necessary.
It was not, strictly speaking, necessary for me to add -r. Plain old sed will work if you say \([0-9]\{0,\}\), but the idea here was to simplify.
sed -i -e 's%<span id="unlockedCount">([0-9]*)</span\>/'"${unlockedCount}/g" index.html
I removed the Useless Use of Cat, took out a bunch of unnecessary backslashes, added single quotes around the regex to protect it from shell expansion, and fixed the repetition operator. You might still need to backslash the grouping parentheses; my sed, at least, wants \(...\).
Note the use of single and double quotes next to each other. Single quotes protect against shell expansion, so you can't use them around "${unlockedCount}" where you do want the shell to interpolate the variable.

How can I trim "/" using shell scripting?

I've been playing around with a little shell script to get some info out of a HTML page downloaded with lynx.
My problem is that I get this string: <span class="val3">MPPTN: 0.9384</span></td>
I can trim the first part of that using:
trimmed_info=`echo ${info/'<span class="val3">'/}`
And the string becomes: "MPPTN: 0.9384"
But how can I trim the last part? Seem like the "/" is messing up with the echo command... I tried:
echo ${finalt/'</span></td>'/};
Not sure if using sed is ok -- one way to extract out the number could be something like ...
echo '<span class="val3">MPPTN: 0.9384</span></td>' | sed 's/^[^:]*..//' | sed 's/<.*$//'
The behavior of ${VARIABLE/PATTERN/REPLACEMENT} depends on what shell you're using, and for bash what version. Under ksh, or under recent enough (I think ≥ 4.0) versions of bash, ${finalt/'</span></td>'/} strips that substring as desired. Under older versions of bash, the quoting is rather quirky; you need to write ${finalt/<\/span><\/td>/} (which still works in newer versions).
Since you're stripping a suffix, you can use the ${VARIABLE%PATTERN} or ${VARIABLE%%PATTERN} construct instead. Here, you're removing everything after the first </, i.e. the longest suffix that matches the pattern </*. Similarly, you can strip the leading HTML tags with ${VARIABLE##PATTERN}.
trimmed=${finalt%%</*}; trimmed=${trimmed##*>}
Added benefit: unlike ${…/…/…}, which is specific to bash/ksh/zsh and works slightly differently in all three, ${…#…} and ${…%…} are fully portable. They don't do as much, but here they're sufficient.
Side note: although it didn't cause any problem in this particular instance, you should always put double quotes around variable substitutions, e.g.
echo "${finalt/'</span></td>'/}"
Otherwise the shell will expand wildcards and spaces in the result. The simple rule is that if you don't have a good reason to leave the double quotes out, you put them.
The solution largely depends on what exactly you want to do. If all your strings are going to be of the form <span class="val3">XXXXX: X.XXXX</span></td>, then the simplest solution is
echo $info | cut -c 20-32
If they're of the form <span class="val3">variable length</span></td>, then the simplest solution is
echo $info | sed 's/<span class="val3">//' | sed 's/<\/span><\/td>//'
If it's more general, you can use regexes like in Sai's answer.
I'd recommend using the sed command for this kind of thing:
echo "$string" | sed "s/$regex/$replace/"

Help with sed regex: extract text from specific tag

First time sed'er, so be gentle.
I have the following text file, 'test_file':
<Tag1>not </Tag1><Tag2>working</Tag2>
I want to extract the text in between <Tag2> using sed regex, there may be other occurrences of <Tag2> and I would like to extract those also.
So far I have this sed based regex:
cat test_file | grep -i "Tag2"| sed 's/<[^>]*[>]//g'
which gives the output:
not working
Anyone any idea how to get this working?
As another poster said, sed may not be the best tool for this job. You may want to use something built for XML parsing, or even a simple scripting language, such as perl.
The problem with your try, is that you aren't analyzing the string properly.
cat test_file is good - it prints out the contents of the file to stdout.
grep -i "Tag2" is ok - it prints out only lines with "Tag2" in them. This may not be exactly what you want. Bear in mind that it will print the whole line, not just the <Tag2> part, so you will still have to search out that part later.
sed 's/<[^>]*[>]//g' isn't what you want - it simply removes the tags, including <Tag1> and <Tag2>.
You can try something like:
cat tmp.tmp | grep -i tag2 | sed 's/.*<Tag2>\(.*\)<\/Tag2>.*/\1/'
This will produce
working
but it will only work for one tag pair.
For your nice, friendly example, you could use
sed -e 's/^.*<Tag2>//' -e 's!</Tag2>.*!!' test-file
but the XML out there is cruel and uncaring. You're asking for serious trouble using regular expressions to scrape XML.
you can use gawk, eg
$ cat file
<Tag1>not </Tag1><Tag2>working here</Tag2>
<Tag1>not </Tag1><Tag2>
working
</Tag2>
$ awk -vRS="</Tag2>" '/<Tag2>/{gsub(/.*<Tag2>/,"");print}' file
working here
working
awk -F"Tag2" '{print $2}' test_1 | sed 's/[^a-zA-Z]//g'