LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 884|回复: 5

awk和sed能否配合起来使用?

[复制链接]
发表于 2005-10-13 22:56:12 | 显示全部楼层 |阅读模式
有两个文件
文件1包含了模式
文件2是待处理文件

想用awk将文件1每行的模式提取出来(比如得到$1,$2),然后用sed在文件2中对每行匹配模式$1,匹配的行在行首插入$2

我写了如下代码
awk '{ sed '/$1/i\$2  infile}' patternfile
但是sed好像不认识$1和$2

改为
awk '{ a=$1;b=$2;sed '/$a/i\$b  infile}' patternfile
也不行

请教应该如何实现啊?
sed是否不能用变量来作为模式?

请大家指教,谢谢!
发表于 2005-10-14 00:12:46 | 显示全部楼层
file1/2是什么内容? 预期的结果啥样?
回复 支持 反对

使用道具 举报

 楼主| 发表于 2005-10-14 07:03:23 | 显示全部楼层
file1
11 Beijing 北京
31 Shanghai 上海

file2
something Beijing
something Shanghai
something Beijing
something Beijing
something Shanghai

预期结果:
北京 something Beijing
上海 something Shanghai
北京 something Beijing
北京 something Beijing
上海 something Shanghai

something代表一些杂乱的不相同的内容
即用file1的每行中的模式来匹配file2中的每行,有两层循环
回复 支持 反对

使用道具 举报

发表于 2005-10-14 08:41:34 | 显示全部楼层
好像可以用 join
回复 支持 反对

使用道具 举报

发表于 2005-10-18 21:59:41 | 显示全部楼层
man awk

  1.                command | getline
  2.                      pipes  a  record  from  command  into  $0 and updates the
  3.                      fields and NF.

  4.                command | getline var
  5.                      pipes a record from command into var.

  6.        Getline returns 0 on end-of-file, -1 on error, otherwise 1.

  7.        Commands on the end of pipes are executed by /bin/sh.
复制代码
回复 支持 反对

使用道具 举报

发表于 2005-10-22 12:10:06 | 显示全部楼层
应该有一个文件要对每一行进行检索才可以吧,写在一个脚本中。


  1. while read num pattern result PATTERN_FILE; do
  2.     sed "/$pattern/i\$result" FILE
  3. done
复制代码


当然也可以利用awk得到列表再做循环
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表