Darvin Rivera Aguilar
Darvin Rivera Aguilar

Reputation: 29

Unix: Replace line with string in another file

File1.txt

1.1.1.1

File2.txt

tcp=ipv4
netmask=255.255.255.0
ip=

Desired Output:

tcp=ipv4
netmask=255.255.255.0
ip=1.1.1.1

I want to replace complete line in File2.txt from File1.txt value searching by "ip=" string.

i try:

sed '/ip=/r File1.txt' File2.txt | sed '/ip=/d'

Output:

tcp=ipv4
netmask=255.255.255.0
1.1.1.1

How to add "ip=" string value to get desired output?

Upvotes: 1

Views: 104

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133780

Could you please try following, written and tested with shown samples in GNU awk. This will handle multiple occurrence/values in file1.txt and fil2.txt too.

awk -F'=' '
BEGIN{ FS=OFS="=" }
FNR==NR{
  arr[++count]=$0
  next
}
/^ip/{
  print $1 OFS arr[++count1]
  next
}
1' file1.txt file2.txt

Explanation: Adding detailed explanation for above.

awk  '                      ##Starting awk program from here.
BEGIN{ FS=OFS="=" }
FNR==NR{                   ##Checking condition FNR==NR which will be TRUE when file1.txt is being read.
  arr[++count]=$0          ##Creating arr with index of increasing value of count and its value is current line.
  next                     ##next will skip all further statements from here.
}
/^ip/{                     ##Checking condition if line starts from ip then do following.
  print $1 OFS arr[++count1]   ##Printing current line and arr with index of increasing value of count1.
  next                     ##next will skip all further statements from here.
}
1                          ##1 will print all lines here.
' file1.txt file2.txt      ##Mentioning Input_file names here.

Upvotes: 3

Beta
Beta

Reputation: 99172

IP=`cat File1.txt`
sed "/^ip=$/s/$/$IP/" File2.txt

Upvotes: 2

Related Questions