0

I have 2250 metadata files that need to have a unique number starting at 0 going to 2249, as the line below.

"name": "KF # RENUMBER",

I've used the perl command (perl -pi -w -e 's/SEARCH_FOR/REPLACE_WITH/g;' *.json) to replace a word with whatever I need in multiple files, but I can't figure out how instead of replacing it with a word, replacing it with the numbers so at the end of the day I have multiple files that have a line like:

"name": "KF # 1",
"name": "KF # 2",
...
"name": "KF # 2249",

I tried perl -pi -w -e 's/RENUMBER/$count++;/g;' *.json

but that returned "name": "KF # ++;", in all the files

I'm using terminal in MacOS to do this, if that is important.

any help would be appreciated! thanks!

2 Answers 2

0

You need to tell Perl that the replacement part is not a string but some code to run:

perl -pi -w -e 's/RENUMBER/++$count/ge' *.json
#                                    ^

"e" is for "evaluate".

Also, if you want to start from 1 and not 0, switch to ++$count.

You can also increment the variable outside of the substitution.

perl -i~ -pwe '++$count; s/RENUMBER/$count/' *.json

This behaves differently if there's more than one RENUMBER per line (the previous replaces each with a different number, this one uses the same number for the whole line). I assumed there's never more than one RENUMBER per line and therefore I removed the /g.

1
  • I used the first instance and it worked great. I was really dreading the tedious task of renumbering over 2000 files so I can't tell you how much I appreciate the help from both who answered. btw, I just took file #0 and edited that manually. just for sake of knocking it out Commented Mar 22 at 19:23
0

You need to add the e flag to your s// expression, which tells perl to evaluate the replace part as an expression:

perl -pi -w -e 's/RENUMBER/$count++;/ge;' *.json

Given three files data{1,2,3}.json each containing:

{
"name": "KF # RENUMBER",
}

Running the above command results in:

$ grep -n . *json
data1.json:1:{
data1.json:2:"name": "KF # 0",
data1.json:3:}
data2.json:1:{
data2.json:2:"name": "KF # 1",
data2.json:3:}
data3.json:1:{
data3.json:2:"name": "KF # 2",
data3.json:3:}
1
  • Thank you for the help! got exactly what I needed Commented Mar 22 at 19:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .