Sed / awk / perl text editing on n lines after match

1

I'm strugling with this. I'm trying to edit the next 6 lines after a match, by adding text before each lines, and double quotes before and after the existing number on each lines.

What my file look like:

"data": [
    4,
    15,
    43,
    10,
    60,
    45

What I'm trying to get as output:

"data": [
    "stuff": "4",
    "stuff": "15",
    "stuff": "20",
    "stuff": "13",
    "stuff": "4",
    "stuff": "25",

I've trying this:

sed '/"data"/{N;N;N;N;N;s/\([0-9][0-9]\)/"stuff": "\1"/}'

But it seems to only edit second line after match. I'm not an expert so I can't figure this out. Any idea / help would be greatly appeciated.

Roxxxance

Posted 2019-06-06T12:59:15.703

Reputation: 11

Does it have to be sed, or have you considered a tool that actually understands JSON structure such as jq? – user1686 – 2019-06-06T13:02:20.617

Note that in JSON, you also need to change [ to {. – choroba – 2019-06-06T13:10:49.820

1I can use any tool, including those who needs some kind of install, as long as it can run on a debian 9. But what I'm trying to achieve with this regexp editing is to convert that json to SQL statement in order to insert it into a database. I found several ways to do that, but each needs flat json; and this is why I'm trying to insert statements before each line that doesn't have one. – Roxxxance – 2019-06-06T15:06:19.620

Answers

1

Code fix:

sed '/"data"/{N;N;N;N;N;N;s/\([0-9][0-9]*\)/"stuff": "\1"/g}'

Test run:

$ sed '/"data"/{N;N;N;N;N;N;s/\([0-9][0-9]*\)/"stuff": "\1"/g}' input.txt
"data": [
    "stuff": "4",
    "stuff": "15",
    "stuff": "43",
    "stuff": "10",
    "stuff": "60",
    "stuff": "45"

Explanation:

You are skipping the first line because you are searching for a double-digit number, and 4 only has one digit. If you want all occurrences to be substituted, you should add the g (global) modifier. Lastly, in order to include the last line, add one more N;


Alternative: Here's a slightly more robust and general Perl:

perl -lape 's/([0-9]+)/"stuff": $1/ if /"data"/../]/'

Alternative: You could edit your input file to make it "flat", and then convert it in one of several ways.


Better alternative: Use jq or some other specialised tool/library to convert JSON files. Do not treat them as text files.

simlev

Posted 2019-06-06T12:59:15.703

Reputation: 3 184