Home > Net >  Multiple Substitution
Multiple Substitution

Time:12-18

I wish to use sed to do mulitple substitutons which are in a names.txt within a JSON file:

Part of the JSON file contains:

{
 "iscomplete": true,
 "totalcount": 3,
 "errcount": 1,
 "requser": "Username",
 "fileimportreqqueueid": 3,
 "format": "JSON",
 "errorfile": "http://host:port/maximo/api/fileimporterrfile/3",
 "_rowstamp": "1521573",
 "iscancelled": false,
 "reqdatetime": "2019-02-20T14:08:22-05:00",
 "name": "[email protected]",
 "href": "http://host:port/maximo/api/os/mxapifileimportqueue/_dGVzdGxvYzMuanNvbg--",
 "pindex": 3,
 "osname": "MXAPIOPERLOC"
}

and part of the names.txt:

[email protected]    Jason.Brady
[email protected]   L.Robson
[email protected]    Mikegraham
[email protected]    Phil.Lewis
[email protected]   LiamH
[email protected]    James.Birch

I tried the following:

#!/bin/bash

while read f ; do

        email=`echo $f |awk '{print $1}' `
        username=`echo $f|awk '{print $2}'`

        sed -i 's!$email!$username!g' file.csv 

done<names.txt

How can I do it ?

Thanks

CodePudding user response:

First, let's convert the email-name pairs into a JSON lookup table.

jq -nR '
   [ inputs | capture("^(?<key>\\S )\\s (?<value>. )") ] |
   from_entries
' names.txt

This produces

{
  "[email protected]": "Jason.Brady",
  "[email protected]": "L.Robson",
  "[email protected]": "Mikegraham",
  "[email protected]": "Phil.Lewis",
  "[email protected]": "LiamH",
  "[email protected]": "James.Bir"
}

Demo on jqplay


This allows us to process the main file easily.

jq --argjson fixes "$(
   jq -nR '
      [ inputs | capture("^(?<key>\\S )\\s (?<value>. )") ] |
      from_entries
   ' names.txt
)" '.name |= ( $fixes[.] // . )' data.json

or

jq --argfile fixes <(
   jq -nR '
      [ inputs | capture("^(?<key>\\S )\\s (?<value>. )") ] |
      from_entries
   ' names.txt
) '.name |= ( $fixes[.] // . )' data.json

(The latter accommodates a larger name mapping file, but requires bash.)

Demo on jqplay


You said you only provided part of the JSON file, so you'll have to adjust the program accordingly. For example, if you have

[ {...}, {...}, {...} ]

You'd replace

.name |= ( $fixes[.] // . )

with

.[].name |= ( $fixes[.] // . )

Demo on jqplay

CodePudding user response:

I suggest taking look at -f option of GNU sed, it should be followed with name of file holding replacement, in your case you might create replacements.sed file with following content

s/jason\.brady@doom\.com/Jason.Brady/g
s/linda\.ribson@doom\.com/L.Robson/g
s/Mike\.graham@doom\.com/Mikegraham/g
s/Phill\.Lewis@doom\.com/Phil.Lewis/g
s/Liam\.Haggard@doom\.com/LiamH/g
s/James\.birch@doom\.com/James.Birch/g

and then

sed -f replacements.sed <file.json

where file.json is name of file with JSON. Output would be that file with replacements applied.

  • Related