Text :

 this *is the* string. 
 this word i want.

Output :

   this *is the* string
   this *is the* word i want

How can I copy "is the" from "this is the string" and paste it between "this word" using either the sed or awk command?


It's easier to use awk for a solution to this kind of problem, and since you tagged the question with awk in addition to sed, here's an awk answer:

awk 'NR==1{data=$2 " " $3}NR==2{$2=data " " $2}{print}'

Missing from your question was guidance how to identify the items to copy, and how you want to identify the position to paste. So, in my answer I took the liberty of assuming you were scanning a first line for its second and third words, with intent to paste them after the first word of the second line.

  • thanks its working. actually i have multiple pair of the input text inside the file. do you know how to loop this awk command? so i can get the same output for other same line. – aweeey Feb 15 '18 at 5:36
  • If the answer is correct, please mark it as correct! If you have another question, you should really post a separate question. To answer your second question anyway, you don't need a "loop"; you can identify all odd lines in awk by replacing NR==1 with just NR%2 (that's a modulus 2 operation) and all even lines by replacing NR==2 with !NR%2. Also, I edited your question to make it more clear, so please also mark that accepted if it is correct. – user1404316 Feb 15 '18 at 5:47

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.