Bash脚本将一个文件中的代码插入另一个文件中的特定位置? [英] Bash script to insert code from one file at a specific location in another file?
问题描述
我有一个带代码段的fileA,并且我需要一个脚本来将该代码段插入到特定模式之后的行中的fileB中.
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
有什么建议吗?
模式(在后一行插入代码段):
pattern (insert snippet on line after):
def boot {
也尝试过逃脱模式,但是没有运气:
also tried escaped pattern but no luck:
def\ boot\ {
def\ boot\ \{
fileA片段:
LiftRules.htmlProperties.default.set((r: Req) =>
new Html5Properties(r.userAgent))
fileB(Boot.scala):
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"))
}
}
推荐答案
sed格式对我来说是正确的.
The sed format looks correct to me.
为帮助您诊断此问题,请尝试使用两个更简单的文本文件和一个简单的模式.
To help you diagnose this, try it with two simpler text files and a simple pattern.
带有模式的文件file:
File filewithpattern:
hello
world
文件文本插入:
foo
goo
现在运行sed:
sed -e '/hello/r textinsert' filewithpattern
您应该看到以下内容:
hello
foo
goo
world
这对您有用吗?
如果是这样,请使用模式编辑filewithpattern以使用目标:
If so, then edit filewithpattern to use your target:
hello
def boot {
world
运行命令:
sed -e '/def boot {/r textinsert' filewithpattern
您应该看到以下内容:
hello
def boot {
foo
goo
world
如果要变量替换,请尝试以下操作:
If you want variable substitution, try this:
#!/bin/bash
PATTERN='def boot {'
sed -e "/${PATTERN}/r textinsert" filewithpattern
这篇关于Bash脚本将一个文件中的代码插入另一个文件中的特定位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!