when i run this command

user@ubuntu:~$ ./2input1output Jojo Ar Dublin

it give me this output

Your First Name: Jojo 
Your Last Name : Ar 
Your Hometown : Dublin
Thank you, Jojo Ar From Dublin,
Welcome to Stackoverflow

Now i need to display the 4 and 5 line from that output then save it in one variable for example i call variable MESSAGE, i have try this

user@ubuntu:~$ (sed -n 4,5p ./2input1output)

but it give me this output

echo"Thank you, $1 $2 From $3,
Welcome to stackoverflow"

Your command is actually working as expected; you are asking sed to return lines 4 and 5 from the file "2input1output". As you can see, the positional arguments (i.e. $1, $2 and $3) are returned because that is what is in the script.

What you need to do is actually run the script first in order to get the desired output (STDOUT) and then pipe that to the stream editor (sed). So, in one hit, to save the desired content to a variable:

$ MESSAGE=$(./2input1output Jojo Ar Dublin | sed -n 4,5p)

Please remember that if you need to preserve newline characters when accessing the variable, wrap it in double quotation marks first.

  • i think your answer is working, but how do i proof that MESSAGE contain line 4 and 5?
    – Aditya
    Oct 14 '18 at 10:04
  • If you're setting the MESSAGE variable on the command line (as per my answer), you can run: echo $MESSAGE Oct 14 '18 at 10:06
  • i dont know how to do that, can you help me again?
    – Aditya
    Oct 14 '18 at 10:36
  • In my answer, we used the variable MESSAGE to store the output of the script and the sed command. In order to see what MESSAGE contains, you can use the "echo" command. To do this, on the command line, type "echo $MESSAGE". Note the "$" sign in front of MESSAGE, this is important as it references the variable not the string. Oct 14 '18 at 10:42

i think sed get fifth line from your script. you can send output to another file then sed lines you want from there or in your bash save output to a variable then grep the lines you want.


We can do it by below method too using awk

MESSAGE=`sh 2input1output Jojo Ar Dublin| awk 'NR >3 && NR<=5 {print $0}'

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.