-1

i want to read whole file in a variable. for example my file is.

file name : Q.txt

My name is Naeem Rehmat.
I am a student of FAST university.
Now i am in 4th semester.
I am learning bash script.
I have this problem.

code:

text=$(cat Q.txt) 
echo $text

out put should be like this:

My name is Naeem Rehmat.
I am a student of FAST university.
Now i am in 4th semester.
I am learning bash script.
I have this problem.
William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • Maybe check the [`bash` tag wiki](http://stackoverflow.com/tags/bash/info) before posting. – tripleee Feb 01 '16 at 06:19
  • Based on comments, I don't think the linked question is a duplicate. I believe the question here is about the fact that process substitution removes the trailing newlines, but it is not at all clear. Note that I edited the question to add formatting to the sample input, and (I think) the question Naeem is having revolves around trailing blank lines in the input file. Naeem, you need to clarify, as your question is unclear. – William Pursell Feb 01 '16 at 15:49

1 Answers1

1

Presumably the problem is that your whitespace is incorrect. Use double quotes:

echo "$text"

When you write echo $text without quotes, bash evaluates the string and performs what is known as "field splitting" or "word splitting" before generating the command. To simplify the case, suppose text is the string foo bar. Bash splits that into two "words" and passes "foo" as the first argument to echo, and "bar" as the second. If you use quotes, bash passes only one argument to echo, and that argument contains multiple spaces which echo will print.

Note that it is probably good style to also use quotes in the assignment of text (ie, text="$(cat Q.txt)"), although it is not necessary since field splitting does not occur in a variable assignment.

William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • thanks for you response. but this does not display file in the same formate i want out put should be with new line. – Naeem Rehmat Feb 01 '16 at 06:24
  • If you use a process substitution (eg `$()`) to read the file, trailing whitespace will be discarded from the file. If you want to retain it, you cannot use `$()` to read the data. But you really need to clarify if that is the problem you are having. – William Pursell Feb 01 '16 at 06:33
  • i want to retain white spaces. – Naeem Rehmat Feb 01 '16 at 06:47