0

How can I replace 'word' on my file for a counter:

{"word":"resolucion","count":40723},{"word":"general","count":20976},
{"word":"","count":13334},{"word":"publica","count":12379},
{"word":"direccion","count":11958},{"word":"secretaria","count":9907},
{"word":"al","count":9324},{"word":"orden","count":8604},
{"word":"anuncia","count":8589},{"word":"concurso","count":6953},
{"word":"diciembre","count":6893},{"word":"adjudicacion","count":6762},
{"word":"estado","count":6154},{"word":"procedimiento","count":5694},
{"word":"julio","count":5598},{"word":"marzo","count":5440},
{"word":"-","count":5437},{"word":"convocatoria","count":5319},
{"word":"ayuntamiento","count":5259},{"word":"publico","count":5203},
{"word":"junio","count":4995},{"word":"convenio","count":4925},
{"word":"real","count":4916},{"word":"febrero","count":4896},
{"word":"proyecto","count":4826},{"word":"abierto","count":4782},

For example:

{"0":"resolucion","count":40723},{"1":"general","count":20976},
{"2":"","count":13334}, {"3":"publica","count":12379},
{"4":"direccion","count":11958},{"5":"secretaria","count":9907},
{"6":"al","count":9324},{"7":"orden","count":8604},
{"8":"anuncia","count":8589},

and so on.

0
0

Here is one possible solution with our grep and sed friends. This is fine for small files, otherwise a perl (or awk?) solution will be much more performant. This is bash syntax:

i=1
maxnum=$(grep -o '\<word\>' datafile | wc -l)
while (( i <= maxnum )); do
  sed -i "s/word/$i/" datafile
  (( i++ ))
done

grep -o counts the total number of word in datafile. This is from Glenn. The only trick here is that sed isn't working globally, so replacing only the first matching string. That's why this code is so slow, as it invokes sed maxnum times on the whole datafile.

Be aware, that sed -i changes your original datafile, so make a copy first.

0

If it's a JSON file, you can use some scripting language to modify it. For example, if you have NodeJS installed, you can run the following program:

var data = require('./data.json')

console.log(data)

data.forEach(function (obj, idx) { obj[idx] = obj['word']; delete obj.word; });

console.log(data)

I assume the file is named 'data.json' and that it's valid JSON syntax (yours isn't quite so: you're missing the wrapping [ ]and you have a spurious , at the end.

0

This should be pretty fast.

perl -0 -ne 's/"word"/q{"} . $x++ . q{"}/ge; print;' INFILE > OUTFILE

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.