shell - use perl to repeat a line fixed no. of times
问题描述
I have a file and i want to repeat some a fixed no. of line below it two times and also to add a loop command just after the second line and end the loop after the second line ends. so my file is
a4 b2 c3 e6
a1 b2 c3 d4
g5 h6 i7 j8
h9 i10 j11 k12
this should become
a4 b2 c3 e6
a1 b2 c3 d4
a1 b2 c3 d4
a1 b2 c3 d4
loop
g5 h6 i7 j8
endloop
h9 i10 j11 k12
I have to do this for 16 files .I am trying to use sed command but it is not working.I am figuring it how to do using perl?
I was trying to use perl -ne 'print $_ x 3' file but it operates on all the lines present in file.
/edit suggested by ikegami/
解决方案
perl -wpe'if ($.==2) { $_ x= 3 } elsif ($.==3) { $_ = "loop\n${_}endloop\n" }' <infile >outfile
or to change multiple files in place:
perl -i -wpe'close ARGV if eof; if ($.==2) { $_ x= 3 } elsif ($.==3) { $_ = "loop\n${_}endloop\n" }' file1 file2 file3
(the close is necessary to restart $.
's line count)
推荐阅读
- jquery - 我正在尝试获取元素并将它们添加到新元素中
- gitlab - Gitlab条件作业执行
- http - 如何监控自己的网络流量?
- kubernetes - Kubernetes yaml 文件不能用作 helm 模板
- r - 需要使用 R 从字符串列中提取单个字符
- dataframe - AWS Glue 动态帧将 csv 写入 s3 且为空
- javascript - 在构造函数中分配的 Sinon 存根类实例
- google-cloud-platform - GCP 上的命名实体识别 (NER)
- python - 仅在 Python asyncio 中处理所有 websocket 消息后返回
- php - 大家好,我在建立连接时遇到错误,谁能帮我解决这个问题......提前谢谢