【问题标题】:sed and "system" in Perl ConcatenationPerl 连接中的 sed 和“系统”
【发布时间】:2018-06-26 21:30:41
【问题描述】:

我正在尝试将文件文本转换为特定格式,因此我使用了很多“sed”

当我在 unix 上尝试所有命令行时,它可以工作,但是当我将命令放入我的脚本 perl 时,如下所示:

system "sed 's/( )//g' prix$arg1.txt>prixmodifAyc.txt";
system "sed 's/ /|/g' prixmodifAyc.txt>prixmodifAyc3.txt";
system "sed 's/||/|/g' prixmodifAyc3.txt>prixmodifAyc4.txt";
system "sed 's/||/|/g' prixmodifAyc4.txt>prixmodifAyc5.txt";
system "sed 's/||/|/g' prixmodifAyc5.txt>prixmodifAyc6.txt";
system "sed 's/||/|/g' prixmodifAyc6.txt>prixmodifAyc7.txt";
system "sed 's/||/|/g' prixmodifAyc7.txt>prixmodifAyc8.txt";
system "sed 's/|€|/|/g' prixmodifAyc8.txt>prixmodifAyc9.txt";
system "sed 's/|key/ key/g' prixmodifAyc9.txt>prixmodifAyc10.txt";
system "sed 's/%|/|/g' prixmodifAyc10.txt>prixmodifAyc11.txt";
system "sed ':a;N;$!ba;s/\n//g' prixmodifAyc11.txt>prixmodifAyc12.txt";

所有行都有效,但不是最后一行,我找不到原因(我根本不是 perl 专家,如果我的帖子无法理解,但英语不是我的主要语言,我真的很抱歉。)

我得到的错误是法语:

sed: -e expression n°1, caractère 10: commande `s' inachevée

我认为这是一个串联问题(因为该命令在终端中有效),但我找不到问题出在哪里,希望有人能够提供帮助

【问题讨论】:

  • 因为它是一个 Perl 脚本,所以我使用“system”在里面使用 unix 命令(它只是脚本的一部分)perldoc.perl.org/functions/system.html
  • 别忘了$\ 是双引号字符串中的特殊字符...
  • 谢谢池上我已经尝试在 $ 之前放一个 \ 但我忘记了 \ 之前它最终出现了哟非常感谢你:)
  • egad,你为什么要从 perl 调用 sed? perl 可以做 sed 可以做的所有事情,而且速度肯定更快,而无需多次调用 shell 和 sed。
  • 您还可以将所有s/||/|/g 替换压缩成一个正则表达式,例如s/|\{2,6\}/|/g

标签: perl unix sed concatenation


【解决方案1】:

不要忘记$\ 是双引号字符串中的特殊字符。您实际上正在执行类似的操作

sed ':a;N;0ba;s/
//g' prixmodifAyc11.txt>prixmodifAyc12.txt

你可以使用

system "sed ':a;N;\$!ba;s/\\n//g' prixmodifAyc11.txt >prixmodifAyc12.txt";

system q{sed ':a;N;$!ba;s/\\n//g' prixmodifAyc11.txt >prixmodifAyc12.txt};

use String::ShellQuote qw( shell_quote );

system(shell_quote('sed', ':a;N;$!ba;s/\\n//g').' prixmodifAyc11.txt >prixmodifAyc12.txt');

【讨论】:

    【解决方案2】:

    $!是上次系统调用返回的错误。

    由于变量扩展确实发生在双引号内,我有根据的猜测是$! 在最后一个sed 命令中扩展,它可能会破坏sed 表达式

    一个简单的解决方法是转义美元符号和转义字符以使其成为文字\

    system "sed ':a;N;\$!ba;s/\\n//g' prixmodifAyc11.txt>prixmodifAyc12.txt";
    

    【讨论】:

    • 我的问题已解决,在 "\" 和 "$" 之前需要一个 \ 非常感谢您的所有回答/评论 :)
    • @ikegami 我在那里看到了这一点..但我很确定操作员从中抓住了这个想法,无论如何都要纠正并感谢你的大眼睛。 :-)
    • @sjsam,实际上,在您将损坏的代码添加到您的答案之前,OP 从对该问题的评论中“抓住了这个想法”。无论哪种方式,指出您的答案需要修正的评论都是合理的。
    猜你喜欢
    • 2021-11-24
    • 2017-03-15
    • 2013-02-14
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-28
    相关资源
    最近更新 更多