sed - 在纯文本文件中每第四行后插入一个逗号
我试图使用 sed 在第 1、4、8 行等的值后面插入一个逗号,
sed '0-4 s/$/,/' in.txt > in2.txt
由于某种原因,这不起作用,所以我想知道是否有人有任何解决方案使用 awk、sed 或任何其他方法来执行此操作。
我收到的错误是
sed: 1: "0-4 s/$/,/": invalid command code -
当前我的数据如下所示:
City Address Zip Code County
并且我试图将其格式化为这样
City, Address Zip Code County
非常感谢。
I am trying to insert a comma after the values on line 1, 4, 8, etc using sed,
sed '0-4 s/$/,/' in.txt > in2.txt
For some reason this isn't working so I was wondering if anyone has any solutions doing this using awk, sed, or any other methods.
The error I am getting is
sed: 1: "0-4 s/$/,/": invalid command code -
Currently my data looks like this:
City Address Zip Code County
and I was trying to format it like this
City, Address Zip Code County
Much Appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
0-4
确实不是格式良好的sed
语法。我会使用awk
来实现此目的,但使用任何一个都可以轻松实现。它替换一行并打印它,然后打印接下来的三行而不替换,然后从脚本的开头重新开始;或者
如果行号模 4 为 1,则进行替换,然后无条件打印。
Sed 的寻址模式有时有点令人失望;没有标准方法来计算相对于或参考文件末尾的行偏移。当然,
awk
更复杂,但如果您只能学习其中之一,那么一定要选择awk
。 (或者在当今时代,Python 或 Perl —— 更好的投资。)0-4
indeed is not well-formedsed
syntax. I would useawk
for this, but it is easy to do it with either.which substitutes one line and prints it, then prints the next three lines without substitution, then starts over from the beginning of the script; or
which does the substitution if the line number modulo 4 is 1, then prints unconditionally.
Sed's addressing modes are sometimes a tad disappointing; there is no standard way to calculate line offsets, relative or in reference to e.g. the end of the file. Of course,
awk
is more complex, but if you can only learn one or the other, definitely go forawk
. (Or in this day and age, Python or Perl -- a much better investment.)这可能对你有用(GNU sed):
This might work for you (GNU sed):