【问题标题】:Insert content of a file to another file on Linux在 Linux 上将文件的内容插入到另一个文件中
【发布时间】:2013-05-15 01:35:35
【问题描述】:

我有两个文件。我想在一些代码之间将第一个文件(file1)的内容插入到第二个文件(file2)中(第二个文件是一个脚本)。例如第二个文件应该是这样的

upcode...
#upcode ends here
file1 content
downcode ...

upcode #upcode ends here 和 downcode 永远不会改变。

如何做到这一点?

【问题讨论】:

  • upcodedowncode 是什么。取决于它们是什么,解决方案可能会改变。
  • 我已经编辑了问题,你是对的。
  • 顺便说一句,如果你想在开头插入file1(因为downcode真的没有任何意义)......做这样的事情 - echo "#!/bin/bash" > file2.tmp; cat file1>> file2.tmp; cat file2 >> file2.tmp; mv file2.tmp file2
  • 完美!谢谢。但是,我希望看到一个通用的解决方案,而不是 #!/bin/bash" 有代码行。
  • 你应该从你的问题中删除#!/bin/sh,因为这对你来说是upcode...对吗?

标签: linux file sed awk cat


【解决方案1】:

你可以试试sed:

sed -e '/file1 content/{r file1' -e 'd}' file2
  • /pattern/: 匹配行的模式
  • r file1: 读取文件1
  • d: 删除行

注意:您可以添加-i 选项来就地更改file2。

【讨论】:

  • 这似乎是一个很好的解决方案,但我不明白。我们在 file2 中搜索一个字符串,例如“#upcode 在此结束”,然后在其后插入 file1 内容,正如我从您的解决方案中越来越了解的那样。为什么我们需要读取 file1?
【解决方案2】:

这是一个执行此操作的脚本(请注意,您的开始标记在文件中必须是唯一的)--

#!/bin/bash

start="what you need"

touch file2.tmp

while read line
do
  if [ "$line" = "$start" ]
  then
     echo "$line" >> file2.tmp
     cat file2 >> file2.tmp
  fi
  echo "$line" >> file2.tmp
done < file1
#mv file2.tmp file1 -- moves (i.e. renames) file2.tmp as file1. 

【讨论】:

    【解决方案3】:
    while IFS= read -r f2line; do
        echo "$f2line"
        [[ "$f2line" = "#upcode ends here" ]] && cat file1
    done < file2 > merged_file
    

    或在原地编辑 file2

    ed file2 <<END
    /#upcode ends here/ r file1
    w
    q
    END
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-24
      • 1970-01-01
      • 1970-01-01
      • 2012-06-09
      • 2011-04-24
      相关资源
      最近更新 更多