将File中的String替换为另一个文件中的1st,2nd ...行

时间:2014-12-03 20:50:57

标签: string replace awk sed line

我在file1中有一个字符串存储为变量。 我需要将file1中的变量替换为另一个文件的第一行 - file2。 停一会儿(15秒左右)所以我用了一些文件 然后用file2的第二行替换file1中的变量。 停一会儿(15秒左右) 对file2的第三行重复上述步骤,依此类推。在用file2中的最后一行替换之后退出。

1 个答案:

答案 0 :(得分:0)

您可以这样做:

#!/bin/bash

while read line; do
  # Using sed is not a good idea if file2 may contain characters that have
  # meaning in a sed regex (or may be your delimiter), and substituting it
  # directly into the awk code would break if there was a quote in there.
  # This should work with everything.
  #
  # Also, we'll need the template file later, so we can't replace in-place.
  # Instead, write the result of the substitution to its own file and work
  # on that.
  awk -v SUBST="$line" '{ gsub("VARIABLE", SUBST, $0); print $0 }' file1 > file1.cooked

  # Instead of sleeping, I encourage you to do the actual work here. That
  # way, you will not introduce brittle timing issues that will vex you when
  # things break in non-obvious ways.
  sleep 15
done < file2