今天学习了一下用awk 处理多个文件,分享一下。
有一个文件 test1.txt内容如下:
- 10.37.212.3 host1
- 10.38.212.52 host2
- 10.39.34.22 host3
另一个文件test2.txt内容如下:
- IP host1
- IP host2
- IP host3
- IP host4
需要将test2.txt 中的hostn 替换成test1.txt 中的相应IP,替换结果应该如下:
- IP 10.37.212.3
- IP 10.38.212.52
- IP 10.39.34.22
- IP host4
第一种方法,适用于2个及其以上的文件处理:
- awk 'FILENAME=="file1"{....}FILENAME=="file2"{....}' file1 file2
- awk 'FILENAME==ARGV[1]{....}FILENAME==ARGV[2]{....}' file1 file2
- awk 'ARGIND==1{....}ARGIND==2{....}' file1 file2
利用上面的方法实现需求:
- awk 'FILENAME=="test.txt" {ar[$2]=$1}; FILENAME=="test2.txt"{if($2 in ar) {print $1,ar[$2]} else {print $0}}' test.txt test2.txt
- awk 'FILENAME==ARGV[1] {ar[$2]=$1}; FILENAME==ARGV[2]{if($2 in ar) {print $1,ar[$2]} else {print $0}}' test.txt test2.txt
- awk 'ARGIND==1 {ar[$2]=$1}; ARGIND==2{if($2 in ar) {print $1,ar[$2]} else {print $0}}' test.txt test2.txt
还有一种方法, 更多的用于2个文件的处理:
- awk 'NR==FNR{处理第一个文本;next}{处理第二个文本}' file1 file2
- awk 'NR==FNR{.....}NR>FNR{....}' file1 file2
利用上面的公式实现需求:
- awk 'NR==FNR{ar[$2]=$1;next}{if($2 in ar) {print $1,ar[$2]} else {print $0}}' test.txt test2.txt
- awk 'NR==FNR{ar[$2]=$1}NR>FNR{if($2 in ar) {print $1,ar[$2]} else {print $0}}' test.txt test2.txt
|