Nev*_*arn 4 command-line bash text-processing
我的问题是关于文本处理:
在列表中,我有以下格式的 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
Run Code Online (Sandbox Code Playgroud)
我需要的输出:
This computer ip address is xxx.xxx.x.xx and is under the name zzzzzzzzzz
Run Code Online (Sandbox Code Playgroud)
如何使用命令行自动将列表中的 IP 和名称复制到输出文件?你能解释一下你的命令吗,因为当我不得不复制/粘贴我不理解的东西时很遗憾。
使用各种文本处理实用程序 ( awk, perl) 和/或流编辑器 ( sed, ed)可能有十几种方法可以做到这一点
一种方法是cut使用冒号分隔符 ( -d:)处的列表,仅保留第二个字段 ( -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
Run Code Online (Sandbox Code Playgroud)
在 中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
Run Code Online (Sandbox Code Playgroud)
-n 在我们要求之前不要打印任何东西/ss: /找到模式ss:(匹配行IP address:)N 也请阅读下一行,以便我们加入他们 ; 分隔命令,就像在 shell 中一样s/old/new/替换old为news/\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
Run Code Online (Sandbox Code Playgroud)
(tee有助于写入newfile并同时显示输出)