【问题标题】:Append text to each of multiple lines in file将文本附加到文件中的多行中的每一行
【发布时间】:2013-11-21 14:09:20
【问题描述】:

我有一个使用唯一标识符对数千行(更准确地说是 28,000 行)执行的查询。 这是(简化的)查询:

update "table1" set event_type = 'NEW' where id=

还有一个文件ids.txt,其中包含要执行更新的行的ID:

10003
10009
....
....
79345
79356

生成的文件应该是这样的:

update "table1" set event_type = 'NEW' where id=10003;
update "table1" set event_type = 'NEW' where id=10009;
...
update "table1" set event_type = 'NEW' where id=79356;

其他除了获取ids.txt文件并使用vim使用全局字符串替换来形成所有28000个查询之外,有没有简单的方法来做到这一点?

【问题讨论】:

    标签: linux bash vim awk


    【解决方案1】:

    使用简单的东西,比如sed:

    sed -r 's/^([0-9]*)$/update "table1" set event_type = \'NEW\' where id=\1/' file
                   |     write back using \1 as placeholder
                 catch digits in the file
    

    上一个答案

    我使用了一种基于 bash 循环的方法,但它有点矫枉过正。查看相关问题:Why is using a shell loop to process text considered bad practice?

    这样循环:

    while read id
    do
       echo "update \"table1\" set event_type = 'NEW' where id=${id};"
    done < ids.txt
    

    它输出:

    $ while read id; do echo "update \"table1\" set event_type = 'NEW' where id=${id};"; done < ids
    update "table1" set event_type = 'NEW' where id=10003;
    update "table1" set event_type = 'NEW' where id=10009;
    ...
    update "table1" set event_type = 'NEW' where id=79345;
    update "table1" set event_type = 'NEW' where id=79356;
    

    【讨论】:

    • 这很快!只需要where id=${id};"; - 每行末尾的分号即可终止 SQL 查询。
    • 哦,那是真的,我没有注意到最后的;。我刚刚更新了你的版本:)
    • @EdMorton 看到这个问题后我刚刚重新访问了这个答案:Why is using a shell loop to process text considered bad practice?。更新表明更好的方法,感谢 cmets!
    • Stéphane (unix.stackexchange.com/users/22565/st%C3%A9phane-chazelas) 的任何与 shell 相关的事情都应该被视为福音。正如 Shell Scripting Recipes 一书 (amazon.com/Shell-Scripting-Recipes-Problem-Solution-Approach/dp/…) 的致谢部分所述,没有人像他一样了解 shell。我不知道他参加了 SO - 如果有人有 shell 问题,他们应该先搜索他的答案!
    • @EdMorton 是的,我同意!他甚至是发现炮击虫的人。他在 Unix & Linux 非常活跃,其实你也应该时不时去那里……关于这里的问题,我想我终于理解了你一年前提到的问题:)
    【解决方案2】:

    仅在处理文本时,编写 shell 循环总是错误的方法。

    在这种情况下,您只需要一个简单的 sed 替换:

    $ cat file
    10003
    10009
    $ sed 's/.*/update "table1" set event_type = '\''NEW'\'' where id=&;/' file
    update "table1" set event_type = 'NEW' where id=10003;
    update "table1" set event_type = 'NEW' where id=10009;
    

    【讨论】:

      【解决方案3】:

      不是全局字符串替换,而是可以在 vim 内部使用

      :%norm Iupdate "table1" set event_type = 'NEW' where id=<ESC>A;
      

      &lt;ESC&gt;Ctrl+v+esc

      【讨论】:

        【解决方案4】:
        sed -i "s/^/update \"table1\" set event_type = 'NEW' where id=/; s/$/;/" id.txt
        

        -i 使更改内联(实际上更改了文件 id.txt)。

        s/^/.../ 将每行的开头 (^) 替换为 ...

        s/$/.../ 将每行 ($) 的末尾替换为 ...

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-11-11
          • 1970-01-01
          • 2014-11-13
          • 1970-01-01
          • 1970-01-01
          • 2013-06-24
          • 2013-09-05
          • 1970-01-01
          相关资源
          最近更新 更多