awk/sub/gsub/ 可能既不是最直接的方法,也不是最简单的方法。当它们有意义时,我喜欢单线:
(1) 在 Perl 中:
172-30-3-163:ajax vphuvan$ perl -pe 's/device.*?=//g' input.txt
"1300", "router 13", "Corp"
"2000", "router 20", "DC1"
where
-p means "print to screen"
-e means execute the statement between the single quotes
s is a regular expression command which gives the instruction to substitute
g is the switch for the regular expression. /g instructs the program to carry out the substitution /device.*?=// wherever applicable
/device.*?=// is an instruction to replace with an empty string '' any expression that starts with the prefix "device" and that ends just before the closest "=" sign. Note that "deviceId", "deviceName" and "deviceLocation" all start with the prefix "device" and each of them ends just before the "=" sign
(2) 在 bash 中:
172-30-3-163:ajax vphuvan$ sed "s/deviceId=//; s/deviceName=//; s/deviceLocation=//" input.txt
"1300", "router 13", "Corp"
"2000", "router 20", "DC1"
在这种情况下,我们指示sed连续运行三个替换指令,其中 "deviceId"、"deviceName" 和 "deviceLocation" 分别替换为空字符串 ''
不幸的是,sed(以及 sub 和 gsub)对正则表达式的支持比 Perl 弱得多,Perl 是完全正则表达式支持的黄金标准。特别是sed和 sub/gsub 都不支持非贪婪指令“?”,这个失败让我的生活变得相当复杂。