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


For example:

{"2":"","count":13334}, {"3":"publica","count":12379},

and so on.


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:

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

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.


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')


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


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.


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.