Gih's Blog

只言片语

很酷的一条命令:比较两个文件特定的行.

2011-06-20 by gihnius, tagged as shell

例如: 比较文件 file1, file2 的前 20行:

diff -u <(sed -n '1,20p' file1) <(sed -n '1,20p' file2) 
以往还折腾awk,perl, 真没想到 diff 能这样用! 从下面的例子看到, diff 是通过两个临时文件进行比较的.
$ diff -u <(sed -n '276,300p' tnrun.pl) <(sed -n '312,350p' tnrun_xml.pl)
--- /tmp/zsh0DiZxS      2011-06-20 17:00:11.000000000 +0800
+++ /tmp/zshFozNfJ      2011-06-20 17:00:11.000000000 +0800
@@ -1,3 +1,22 @@
+
+        (defined $infos[0])?($hosts[$n]->{ip} = $infos[0]):($hosts[$n]->{ip} = undef);
+        (defined $infos[1])?($hosts[$n]->{user} = $infos[1]):($hosts[$n]->{user} = undef);
+        (defined $infos[2])?($hosts[$n]->{pass} = $infos[2]):($hosts[$n]->{pass} = undef);
+        $n++;
+    }
+    close (HOSTS);
+    return @hosts;
+}
+
+## get cmd list in file
+sub get_cmd_from_file {
+    my @cmds;
+    open (CMDS, "<$_[0]") || die "failed to open cmd list file: $!";
+    while (my $cmd = <CMDS>) {
+        chomp ($cmd);
+        push (@cmds, $cmd);
+    }
+    close CMDS;
     return @cmds;
 }
 
@@ -18,8 +37,3 @@
     my $runh = 0;
 
     if ($by_hosts_file) {
-        @tn_ips = get_ip_from_file($hosts_file);
-    }
-    if ($by_cmd_file) {
-        @cmds = get_cmd_from_file($cmd_file);
-    }
$ 
这就是说, <() 可以建立临时文件, 试试这个命令
 cat <(cat .profile) 
你会看到cat输出的是 .profile的内容. 接着
 echo $_ 
会输出 /tmp/zshOuJC2d 类似的内容, 表示一个临时文件. 也就是说上一个命令等于执行
 cat /tmp/zshOuJC2d