0

I want to save dynamic multiline input from command line to a file in the same format as input.

For Eg:

Code to get the dynamic input:

echo "Enter the multi-line message"
message=$(sed '/one.*/q')
echo $message > Finalinput.txt

If i give the input message as below,

Subject: Subject for the file
Date: Friday, June 11, 2016 @ 02:00am - 06:00am 
Time: 02:00am - 06:00am 


Test message Test message Test message Test message Test message
Test message Test message Test message Test message Test message
Test message Test message Test message Test message Test message
Test message Test message Test message Test message Test message
Test message Test message Test message Test message Test message
Test message Test message Test message Test message Test message

Sincerely,
xxxxx

Then the Finalinput.txt should also be in the same format like above but instead it is showing as

Subject: Subject for the file Date: Friday, June 11, 2016 @ 02:00am - 06:00am Time: 02:00am - 06:00am Test message Test message Test message Test message Test messageTest message Test message Test message Test message Test messageTest message Test message Test message Test message Test messageTest message Test message Test message Test message Test messageTest message Test message Test message Test message Test messageTest message Test message Test message Test message Test message
Sincerely,
xxxxx

Because of this problem, sed commands are replacing some wrong pattern. Kindly help me to save the dynamic input from command line to a file in the same format as input using Shell script

Kusalananda
  • 333,661

1 Answers1

1

The problem lies with echo as it will not do the right thing. You should use double quotes around the variable or the newlines will not be preserved:

echo "$message" >Finalinput.txt

If you want, you could do it in a number of different ways too, depending on your needs. The following puts the text into the message variable, but also writes it to the file in one go:

message="$( sed '/one.*/q' | tee Finalinput.txt )"

The sed command will get the input from the user and pass it to tee which will duplicate it, once to Finalinput.txt and once into the message variable.

If there isn't a need for keeping the text in a variable at all, then just

sed '/one.*/q' >Finalinput.txt

will work just as good.

Kusalananda
  • 333,661