加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

bash – Unix代码想复制模板文件并替换复制文件中模板文件中的字

发布时间:2020-12-15 22:25:35 所属栏目:安全 来源:网络整理
导读:我有2个文件: File_1.txt: JohnMaryHarryBill File_2.txt: My name is ID,and I am on line NR of file 1. 我想创建四个看起来像这样的文件: Output_file_1.txt: My name is John,and I am on line 1 of file 1. Output_file_2.txt: My name is Mary,a
我有2个文件:

File_1.txt:

John
Mary
Harry
Bill

File_2.txt:

My name is ID,and I am on line NR of file 1.

我想创建四个看起来像这样的文件:

Output_file_1.txt:

My name is John,and I am on line 1 of file 1.

Output_file_2.txt:

My name is Mary,and I am on line 2 of file 1.

Output_file_3.txt:

My name is Harry,and I am on line 3 of file 1.

Output_file_4.txt:

My name is Bill,and I am on line 4 of file 1.

通常我会使用以下sed命令来执行此操作:

for q in John Mary Harry Bill
do  
sed 's/ID/'${q}'/g' File_2.txt > Output_file.txt
done

但这只会替换名称的ID,而不包括File_1.txt的行号.不幸的是,我的bash技能没有比这更进一步……对于包含文件1和2的命令的任何提示或建议?我确实需要包含文件1,因为实际上文件比这个例子大得多,但我想如果我知道如何用这个希望更简单的例子来解决其余的代码……很多提前致谢!

解决方法

怎么样:

n=1
while read q
  do  
  sed -e 's/ID/'${q}'/g' -e "s/NR/$n/" File_2.txt > Output_file_${n}.txt
  ((n++))
done < File_1.txt

有关详细信息,请参阅Advanced Bash Scripting Guide on redirecting input to code blocks和the section on double parentheses.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读