如何按顺序编辑多个文件的相同两行?
我有一组元数据,需要
- 在每个字段上编辑带有序列号第 2 行的字段: <前><代码>“名称”:“#1”
- 每行第 5 行: <前><代码>“版本”:1,
我需要用 580 个文件中的连续数字替换每行上的 1。
这就是我想要完成的任务:
1.json
{
"name": "#1",
"description": "description",
"image": "imagelink",
"edition": 1,
2.json
{
"name": "#2",
"description": "description",
"image": "imagelink",
"edition": 2,
3.json
{
"name": "#3",
"description": "description",
"image": "imagelink",
"edition": 3,
等
我正在尝试修改此处的代码以适合我的场景:
我尝试过
perl -pi -e '$_ = sprintf("name": %01d %s", ++$n, $_) if $. == 1; close ARGV if eof' *.json
当我尝试这个时,我没有在任何文件中得到任何更改。
I have a set of metadata where I need to edit the fields with a sequential number
- Line 2 on each:
"name": "#1"
- Line 5 on each:
"edition": 1,
I need to replace 1 on each line with sequential numbers in 580 files.
This is what I am trying to accomplish:
1.json
{
"name": "#1",
"description": "description",
"image": "imagelink",
"edition": 1,
2.json
{
"name": "#2",
"description": "description",
"image": "imagelink",
"edition": 2,
3.json
{
"name": "#3",
"description": "description",
"image": "imagelink",
"edition": 3,
etc
I am trying to modify the code here to work for my scenario:
I tried
perl -pi -e '$_ = sprintf("name": %01d %s", ++$n, $_) if $. == 1; close ARGV if eof' *.json
When I try this I dont get any change in any of the files.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在处理格式时,使用真正理解 JSON 的方法总是更容易、更可靠。以下使用了几个非核心模块, Path::Tiny 和 JSON::MaybeXS (如果您使用 Homebrew 进行 Mac 包管理,我看不到它们可用的但您可以安装
cpanminus
然后执行cpanm Path::Tiny JSON::MaybeXS
安装它们。)It's always easier and more robust to use an approach that actually understands JSON when working with the format. The following uses a couple of non-core modules, Path::Tiny and JSON::MaybeXS (If you're using homebrew for Mac package management, I don't see them available but you can install
cpanminus
and then do acpanm Path::Tiny JSON::MaybeXS
to install them.)以下代码片段解决了我的问题:
第一个解决了将 #1 替换为 #(序号) 的问题
第二个解决了将 : 1 (在第 5 行中找到) 替换为 :(序号) 的问题
The following code snippets solved my problem:
The first addressed the issue of replacing #1 with #(sequential numbers)
The second addresses the issue of replacing : 1 (found in line 5) with :(sequential numbers)