开发者

End of line in shell variables

开发者 https://www.devze.com 2023-03-24 19:51 出处:网络
So I have testfile which contains Line one Another line and this is the third line My script reads this file, does some stuff and I end up with a variable that should contain it. Kind of doing

So I have testfile which contains

Line one
Another line
and this is the third line

My script reads this file, does some stuff and I end up with a variable that should contain it. Kind of doing

filevar=$(cat testfile)

(the important thing here is that I cannot access the file directly).

I'll be using the contents of that variable to generate an HTML code and one things I have to do is to add <br> to t开发者_开发百科he end of each line. The problem is, there doesnt seem to any EOLs in my var:

echo $filevar
Line one Another line and this is the third line

How do I read the file properly to keep the EOLs? Once I have that I can simply sed s/$/<br>/g, but till then...

thanks!


how about changing IFS?

#!/bin/bash

IFS=""
filevar=$(cat test)
echo $filevar

this will output:

Line one
Another line
and this is the third line


I can't understand why do you need to read the file into the variable. Why don't you simply do this:

sed 's|$|<br/>|' testfile 

UPDATE:

If you really want to get the EOL back in your variable. Try this (notice the quotes):

echo "$filevar"

But I still can't understand, why you can cat the file but not access the file

As a solution, I would suggest the following script:

while read LINE
do
  echo ${LINE} '<br />'   # Implement your core logic here.
done < testfile


Instead of doing echo $filevar do echo "$filevar" (note the double quotes). This will send a single argument to echo and then you can pipe this to sed.

With sed, this will be treated as 3 lines, so you do not need the g option. This works with me (bash and cygwin):

echo "$filevar" | sed 's/$/<br>/'


You need to set the IFS variable to contain just a newline, and then reference the filevar variable without quotes.

$ filevar='Line one
Another line
and this is the third line'

$ for word in $filevar; do echo "$word<br>"; done
Line<br>
one<br>
Another<br>
line<br>
and<br>
this<br>
is<br>
the<br>
third<br>
line<br>

$ for word in "$filevar"; do echo "$word<br>"; done
Line one
Another line
and this is the third line<br>

$ (IFS=$'\n'; for word in $filevar; do echo "$word<br>"; done)
Line one<br>
Another line<br>
and this is the third line<br>
0

精彩评论

暂无评论...
验证码 换一张
取 消