0

I have two files, whose line numbers are not same. But in file1 I want to replace lines taking reference from file2 using sed command.

In file1:

tid.infno := 72
tid.setnr := 120 (This number 120 is wrong and It will be 110)
tid.typeidc := 2
tid.typeidm := 1
writedb
clear

In file2:

tid.setnr := 110 (This is correct and I want to place this number in file no. 1)
1

A awk solution:

awk 'FNR==NR&&$1=="tid.setnr"{x=$3} NR!=FNR{if($1=="tid.setnr"){$3=x}print}' file2 file1
  • First part: FNR==NR&&$1=="tid.setnr"{x=$3}: Run through file2 and search for tid.setnr, if found the a variable x to the value (110).
  • Second part: NR!=FNR{if($1=="tid.setnr"){$3=x}print}: Run trought file1, search for tid.setnr, and if found replace the 3rd field ($3) with the found number in the other file.
0

First extract number from file-2 and save it as a variable:

correctNo=`grep -oP "setnr\s\:\=\s\K\d+" file2.txt`

Then replace this number in the file-1:

sed -re "s/(setnr\s\:\=\s)([0-9]+)/\1$correctNo/g" file1.txt
0

How about this:

$ for line in `cat file2.txt`; do
pattern= `sed "s/\s*:=.*//"`
sed "s/$pattern.*/$line/" file1.txt > file3.txt
done

The code will create file3.txt with lines from file1.txt, any lines that match the pattern from file2.txt will be replaced with the lines from file2.txt

I make quite a few assumptions here... the above will look for "tid.setnr" in file1 and replace the entire line with the line from file2.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.