shell脚本剪切和sed帮助

时间:2010-09-14 07:32:26

标签: linux shell

我有两个文件

$cat file1.txt
 field1=value1
 field2=value2
 field3=value3
 ::
 ::

 $cat file2.txt
 something.field1.some
 otherthing.field2.anything
 anything.field3.something

我需要读取file1.txt并检查fileN的file2.txt是否为valueN

这样结果将是

  something.value1.some
  otherthing.value2.anything
  anything.value3.something

3 个答案:

答案 0 :(得分:4)

如果您的字段和值中没有特殊的sed - 类型字符,则可以使用meta-sed方法:

pax> sed -e 's/^/s\/\\./' -e 's/=/\\.\/./' -e 's/$/.\/g/' file1.txt >x.sed
pax> sed -f x.sed file2.txt

something.value1.some
otherthing.value2.anything
anything.value3.something

如果查看x.sed文件,您会看到第一个sed只列出了要在第二个文件上执行的sed命令。

答案 1 :(得分:2)

使用awk

$ awk -F"[=.]" 'FNR==NR{a[$1]=$2;next}{$2=a[$2]}1' OFS="." file1 file2
something.value1.some
otherthing.value2.anything
anything.value3.something

答案 2 :(得分:0)

遗憾的是,这需要对文件进行排序:

tr = . < file1.txt | join -t . -1 1 -2 2 -o 2.1 1.2 2.3 - file2.txt