【问题标题】:Convert sed One-Liner to perl将 sed One-Liner 转换为 perl
【发布时间】:2014-05-08 21:20:21
【问题描述】:

我在我的perl 脚本中使用了这个sed 单行。但是,有没有办法(我相信有)在 perl 中做同样的工作?

这是我的文件:

$ cat all_log1.txt 
Looking into the table etl_f_gl_balance
# of -1 values in  etl_f_gl_balance.row_key:
0
# of -1 values in  etl_f_gl_balance.ledger_key:
1020
# of -1 values in  etl_f_gl_balance.gl_account_key:
1020
# of -1 values in  etl_f_gl_balance.legal_entity_key:
1020
# of -1 values in  etl_f_gl_balance.cost_center_key:
995
# of -1 values in  etl_f_gl_balance.natural_account_key:
1020
# of -1 values in  etl_f_gl_balance.posting_period_fiscal_key:
5
# of -1 values in  etl_f_gl_balance.posting_period_key:
5

我想要如下输出,这是我的sed 解决方案:

$ sed ':a; N; $!ba; s/:\n/: /g' all_log1.txt 
Looking into the table etl_f_gl_balance
# of -1 values in  etl_f_gl_balance.row_key: 0
# of -1 values in  etl_f_gl_balance.ledger_key: 1020
# of -1 values in  etl_f_gl_balance.gl_account_key: 1020
# of -1 values in  etl_f_gl_balance.legal_entity_key: 1020
# of -1 values in  etl_f_gl_balance.cost_center_key: 995
# of -1 values in  etl_f_gl_balance.natural_account_key: 1020
# of -1 values in  etl_f_gl_balance.posting_period_fiscal_key: 5
# of -1 values in  etl_f_gl_balance.posting_period_key: 5

目前,无论我使用哪种正则表达式组合,我都无法在 perl 中完成它。因此,我最终在我的perl 脚本中调用了这个sed 命令。

我不是在寻找 perl 脚本,而是在寻找单线。

谢谢。

【问题讨论】:

  • 那么到目前为止,您尝试了什么? perl -pe's/:\n/: /' 没有用吗?
  • 我不会发布输出,但s2p ':a; N; $!ba; s/:\n/: /g' 很有趣:s2p - sed to perl translator
  • FWIW,您原来的sed 命令可以简化为'1 ! {N; s/:\n/: /g}''/^#/ {N; s/:\n/: /g}'

标签: regex perl bash sed


【解决方案1】:

这个会备份当前文件并更新它:

perl -i.bak -pe 's/\n$/ /g if /^#/gm' all_log1.txt

如果你想在屏幕上有输出,那么使用这个:

perl -pe 's/\n$/ /g if /^#/gm' all_log1.txt

【讨论】:

  • 但您的原始文件已更改。可以打开查看
  • 如果你想打印结果,你可以使用-pe标志代替
【解决方案2】:

这个 perl 单行应该可以工作:

perl -pe 's/:\n$/: /' file
Looking into the table etl_f_gl_balance
# of -1 values in  etl_f_gl_balance.row_key: 0
# of -1 values in  etl_f_gl_balance.ledger_key: 1020
# of -1 values in  etl_f_gl_balance.gl_account_key: 1020
# of -1 values in  etl_f_gl_balance.legal_entity_key: 1020
# of -1 values in  etl_f_gl_balance.cost_center_key: 995
# of -1 values in  etl_f_gl_balance.natural_account_key: 1020
# of -1 values in  etl_f_gl_balance.posting_period_fiscal_key: 5
# of -1 values in  etl_f_gl_balance.posting_period_key: 5

【讨论】:

  • e 开关是需要直接写命令到命令行这里用什么?
  • 此处用于相同目的。用-e 试试上面的命令,你就知道了。
  • 使用-e 什么也不打印,文件也保持不变
  • @aelor 这是在'...' 中编写的 Perl 代码。这就是 Perl 的魅力。
猜你喜欢
  • 2011-06-01
  • 2017-06-12
  • 2014-07-31
  • 2015-03-03
  • 2016-11-22
  • 2015-05-16
  • 2014-03-19
  • 2017-08-22
  • 2013-09-02
相关资源
最近更新 更多