catchvenki
catchvenki

Reputation: 35

Append values from one file to another using sed or awk

i have a file say file1 with the following data

1.1.1.1
2.2.2.2
3.3.3.3
testserver.test.com
4.4.4.4
255.255.255.0

i want the first two ip's to add in say file2 in the below format

Expected output (file2)

DNS1=1.1.1.1
DNS2=2.2.2.2

Kindly help

Upvotes: 0

Views: 106

Answers (3)

James Brown
James Brown

Reputation: 37394

Another in awk:

$ awk '$0="DNS" ++i "=" $0; NR==2{exit}' file 
DNS1=1.1.1.1
DNS2=2.2.2.2

Explained:

  • $0="DNS" ++i "=" $0 modifies $0 by prepending text to the beginning and uses the result of the placement for implicit print
  • NR==2{exit} exits after the second record output

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133428

@catchvenki:try: A very slightly different(but inspired from Inian's code) from Inian's nice solution.

 awk 'FNR==1||FNR==2{print "DNS"FNR"="$0}'    Input_file > Output_file

I am directly printing here lines in spite of taking them to $0 and then print, then after printing all the lines putting them into Output_file.

Upvotes: 1

Inian
Inian

Reputation: 85550

You could use an Awk statement as below,

awk 'NR==1||NR==2{$0="DNS"NR"="$0; print}' file1 > file2

am using the awk in-built variable NR to keep track on the line numbers 1 and 2 and add the string DNS with line number and printing the contents to file2.

Upvotes: 1

Related Questions