sed在每4行末尾添加逗号

时间:2015-03-21 20:27:02

标签: linux unix sed

我需要在每四行的末尾添加一个逗号。这是一个输出的例子,后面是我要找的东西。

("tester1",
"SERVICE_TICKET_CREATED",
"Thu Mar 19 23:27:57 UTC 2015",
"73.217.129.159")
("tester1",
"SERVICE_TICKET_CREATED",
"Fri Mar 20 00:31:59 UTC 2015",
"73.217.129.159")

我需要什么

("tester1",
"SERVICE_TICKET_CREATED",
"Thu Mar 19 23:27:57 UTC 2015",
"73.217.129.159"),
("tester1",
"SERVICE_TICKET_CREATED",
"Fri Mar 20 00:31:59 UTC 2015",
"73.217.129.159"),

3 个答案:

答案 0 :(得分:3)

如果您的目标是在每次结束后添加逗号,那么您可以执行以下操作:

sed 's/)$/),/'

这将适应行数不同的记录。

答案 1 :(得分:2)

使用awk

awk非常适合这个:

$ awk '0==NR%4{$0=$0","} 1' file
("tester1",
"SERVICE_TICKET_CREATED",
"Thu Mar 19 23:27:57 UTC 2015",
"73.217.129.159"),
("tester1",
"SERVICE_TICKET_CREATED",
"Fri Mar 20 00:31:59 UTC 2015",
"73.217.129.159"),

工作原理:

  • 0==NR%4{$0=$0","}

    NR是行号。 NR%4是以4为模的行号。因此,每隔四行0 == NR%4。对于这些行,我们在末尾添加逗号:$0=$0","

  • 1

    这是awk用于打印线的神秘简写。

使用sed

看起来你想在每一行以一个近似的parens结尾后用逗号。如果是这种情况,那么:

$ sed 's/)$/),/' file
("tester1",
"SERVICE_TICKET_CREATED",
"Thu Mar 19 23:27:57 UTC 2015",
"73.217.129.159"),
("tester1",
"SERVICE_TICKET_CREATED",
"Fri Mar 20 00:31:59 UTC 2015",
"73.217.129.159"),

答案 2 :(得分:1)

你可以用“)”,“使用这个sed命令:

来替换任何结尾”)“
sed 's/)$/),/' <your file>