从多行文件复制特定文本,并使用终端自动将其粘贴到另一个文件中

我的问题是关于文本处理:

在列表中,我有以下格式的IP地址和计算机名称:

IP address: 192.168.1.25 Computer name: computer7office IP address: 192.168.1.69 Computer name: computer22office IP address: 192.168.1.44 Computer name: computer12personal 

我需要的输出:

 This computer ip address is xxx.xxx.x.xx and is under the name zzzzzzzzzz 

如何使用命令行自动将列表中的IP和名称复制到输出文件? 你能否解释一下你的命令,因为当我必须复制/粘贴我不理解的东西时,我很遗憾。

sed ,假设您的列表位于名为file ,您可以使用:

 sed -n '/ss: /N;s/\n//;s/IP address:/This computer ip address is/;s/Computer name:/ and is under the name/p' file 
  • -n在我们要求之前不要打印任何东西
  • /ss: /找到模式ss:以匹配具有IP address:的行IP address:
  • N读了下一行,所以我们可以加入它们
  • ; 分隔命令,就像在shell中一样
  • s/old/new/old替换old
  • s/\n//删除两行之间的换行符
  • p打印我们工作的线条

当您看到所需内容时,请在其末尾重复添加> newfile命令,将修改后的文件写入newfile

更可读:

 sed -n '{ /ss: /N s/\n// s/IP address:/This computer ip address is/ s/Computer name:/ and is under the name/p }' file | tee newfile 

tee写入新文件并同时显示输出)

使用各种文本处理实用程序( awkperl )和/或流编辑器( seded )可能有十几种方法可以做到这一点

一种方法是在冒号分隔符( -d: cut列表,仅保留第二个字段( -f2 ),然后使用xargs将行对( -l2 )作为参数传递给printf

 $ cut -d: -f2 list.txt | xargs -l2 printf 'This computer ip address is %s and is under the name %s\n' This computer ip address is 192.168.1.25 and is under the name computer7office This computer ip address is 192.168.1.69 and is under the name computer22office This computer ip address is 192.168.1.44 and is under the name computer12personal