【问题标题】:How can I use perl/awk/sed to search for all occurrences of text wrapped in quotes within a file and then delete them?如何使用 perl/awk/sed 在文件中搜索所有出现在引号中的文本,然后删除它们?
【发布时间】:2025-11-24 06:15:02
【问题描述】:

如何使用 perl、awk 或 sed 搜索文件中所有出现在引号中的文本,并打印从文件中删除这些出现的结果?我不想实际更改文件,而只是像 sed 一样打印更改文件的结果。

例如,假设文件包含以下内容:

data|more data|"not important"|"more unimportant stuff"

我需要打印出来:

data|more data||

但我想保持文件完整。我尝试使用 sed,但无法让它接受正则表达式。

我尝试过这样的事情:

sed -e 's/\<["]+[^"]*["]+\>//g' file.txt

但它什么也不做并打印原始文件。 有什么想法吗?

【问题讨论】:

    标签: regex perl shell sed ksh


    【解决方案1】:

    您的sed 命令中似乎有一些额外的字符。

    sed -e 's/"[^"]*"//g' file.txt
    

    输入:

    "quoted text is here" but not quoted there
    never more
    "hello world" foo bar
    data|more data|"not important"|"more unimportant stuff"
    

    输出:

     but not quoted there
    never more
     foo bar
    data|more data||
    

    【讨论】:

    • 正如皮埃尔在回答中所说,您不需要这么多括号。
    【解决方案2】:
    echo 'data|more data|"not important"|"more unimportant stuff"' | sed -E 's/"[^"]*"//g'
    

    你不需要为一个字符声明一个字符类(括号)...

    【讨论】:

    • 我确实希望它也删除双引号或三引号中的字符串。我应该提到这一点。
    • 那这不是办法。考虑以下示例:“我明天要去上学”...您将删除“我”并从下一个“开始删除内容”
    • 我可以保证文件中没有单引号。双引号只是多次出现。
    【解决方案3】:

    使用 perl 单行:

    perl -pe 's/".*?"//g' file
    

    说明:

    开关

    • -p:为输入文件中的每一行创建一个 while(&lt;&gt;){...; print} 循环。
    • -e:告诉perl 在命令行上执行代码。

    【讨论】:

      【解决方案4】:
      my $cnt=qq(data|more data|"not important"|"more unimportant stuff");
      my @arr = $cnt =~ m{(?:^|\|)([^"][^\|]*[^"])(?=\||$)}ig;
      print "@arr";
      

      此代码可能会对您有所帮助..

      【讨论】:

      • 很高兴能解释一下您的解决方案。指定您使用的语言对读者也很重要。
      最近更新 更多