Bash script to insert code from one file at a specific location in another file?

瘦欲@ 提交于 2020-02-02 15:22:51

问题


I have a fileA with a snippet of code, and I need a script to insert that snippet into fileB on the line after a specific pattern.

I'm trying to make the accepted answer in this thread work, but it's not, and is not giving an error so not sure why not:

sed -e '/pattern/r text2insert' filewithpattern

Any suggestions?

pattern (insert snippet on line after):

def boot {

also tried escaped pattern but no luck:

def\ boot\ {
def\ boot\ \{

fileA snippet:

    LiftRules.htmlProperties.default.set((r: Req) =>
        new Html5Properties(r.userAgent))

fileB (Boot.scala):

package bootstrap.liftweb
import net.liftweb._
import util._
import Helpers._
import common._
import http._
import sitemap._
import Loc._


/**
 * A class that's instantiated early and run.  It allows the application
 * to modify lift's environment
 */
class Boot {
  def boot {
    // where to search snippet
    LiftRules.addToPackages("code")

    // Build SiteMap
    val entries = List(
      Menu.i("Home") / "index", // the simple way to declare a menu

      // more complex because this menu allows anything in the
      // /static path to be visible
      Menu(Loc("Static", Link(List("static"), true, "/static/index"), 
           "Static Content")))

    // set the sitemap.  Note if you don't want access control for
    // each page, just comment this line out.
    LiftRules.setSiteMap(SiteMap(entries:_*))

    // Use jQuery 1.4
    LiftRules.jsArtifacts = net.liftweb.http.js.jquery.JQuery14Artifacts

    //Show the spinny image when an Ajax call starts
    LiftRules.ajaxStart =
      Full(() => LiftRules.jsArtifacts.show("ajax-loader").cmd)

    // Make the spinny image go away when it ends
    LiftRules.ajaxEnd =
      Full(() => LiftRules.jsArtifacts.hide("ajax-loader").cmd)

    // Force the request to be UTF-8
    LiftRules.early.append(_.setCharacterEncoding("UTF-8"))

  }
}

回答1:


The sed format looks correct to me.

To help you diagnose this, try it with two simpler text files and a simple pattern.

File filewithpattern:

hello
world

File textinsert:

foo
goo

Now run sed:

sed -e '/hello/r textinsert' filewithpattern

You should see this:

hello
foo
goo
world

Does that work for you?

If so, then edit filewithpattern to use your target:

hello
def boot {
world

Run the command:

sed -e '/def boot {/r textinsert' filewithpattern

You should see this:

hello
def boot {
foo
goo
world

If you want variable substitution, try this:

#!/bin/bash
PATTERN='def boot {'
sed -e "/${PATTERN}/r textinsert" filewithpattern


来源:https://stackoverflow.com/questions/10050330/bash-script-to-insert-code-from-one-file-at-a-specific-location-in-another-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!