gpt4 book ai didi

sed - 查找并替换为相同的通配符

转载 作者:行者123 更新时间:2023-12-04 19:51:24 24 4
gpt4 key购买 nike

我想用通配符搜索并用相同的通配符替换。例如搜索特定的水果名称并在不同位置用相同的名称替换它。

输入:

fruit_id "Apple"; salad_id ""; 
fruit_id "Mango"; salad_id "";
fruit_id "Kiwi"; salad_id "";

预期输出:

fruit_id "Apple"; salad_id "Apple"; 
fruit_id "Mango"; salad_id "Mango";
fruit_id "Kiwi"; salad_id "Kiwi";

我正在使用 sed 并且由于显而易见的原因它不起作用:

sed 's/fruit_id "..*"; salad_id "";/fruit_id "..*"; salad_id "..*";/g'

最佳答案

您可以捕获部分并在替换中使用占位符来引用捕获的值:

sed 's/\(fruit_id "\([^"]*\)"; salad_id \)"";/\1"\2";/g' file > newfile

详细信息:

  • \(fruit_id "\([^"]*\)"; salad_id\) - 第 1 组(\1):
    • fruit_id " - fruit_id " 子串
    • \([^"]*\) - 第 2 组 (\2):" 以外的任何 0+ 个字符
    • "; salad_id - "; salad_id 子串
  • ""; - ""; 子字符串。

参见 online demo :

s='fruit_id "Apple"; salad_id ""; 
fruit_id "Mango"; salad_id "";
fruit_id "Kiwi"; salad_id "";'

sed 's/\(fruit_id "\([^"]*\)"; salad_id \)"";/\1"\2";/g' <<< "$s"

输出:

fruit_id "Apple"; salad_id "Apple"; 
fruit_id "Mango"; salad_id "Mango";
fruit_id "Kiwi"; salad_id "Kiwi";

关于sed - 查找并替换为相同的通配符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57608543/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com