开发者

shell script cut and sed help

开发者 https://www.devze.com 2023-01-15 21:16 出处:网络
I have 2 two files $cat file1.txt field1=value1 field开发者_StackOverflow社区2=value2 field3=value3

I have 2 two files

$cat file1.txt
 field1=value1
 field开发者_StackOverflow社区2=value2
 field3=value3
 ::
 ::

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

I need to read file1.txt and check whether file2.txt for fieldN and replace with valueN

so that the result will be

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


Provided there are no special sed-type characters in your fields and values, you can use a meta-sed approach:

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

If you look at the x.sed file, you'll see that the first sed just makes a list of sed commands to be executed on your second file.


use 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


This unfortunately requires the files to be sorted:

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

精彩评论

暂无评论...
验证码 换一张
取 消