shell变量中的行尾

时间:2011-08-03 17:34:36

标签: string shell sed

所以我有testfile包含

Line one
Another line
and this is the third line

我的脚本读取此文件,执行一些操作,最后得到一个应该包含它的变量。做的那种

filevar=$(cat testfile)

(这里重要的是我无法直接访问该文件)。

我将使用该变量的内容生成HTML代码,我要做的一件事就是将<br>添加到每行的末尾。问题是,我的var中似乎没有任何EOL:

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

如何正确阅读文件以保留EOL?一旦我有了,我可以简单地sed s/$/<br>/g,但直到那时......

谢谢!

4 个答案:

答案 0 :(得分:4)

如何改变IFS?

#!/bin/bash

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

这将输出:

Line one
Another line
and this is the third line

答案 1 :(得分:1)

您需要将IFS变量设置为仅包含换行符,然后在不带引号的情况下引用filevar变量

$ 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>

答案 2 :(得分:1)

我无法理解你为什么需要将文件读入变量。你为什么不这样做:

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

<强>更新

如果你真的想让EOL回到你的变量中。试试这个(注意引号):

echo "$filevar"

但我仍然无法理解,为什么你可以cat该文件但不能访问该文件

作为解决方案,我建议使用以下脚本:

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

答案 3 :(得分:1)

而不是echo $filevar执行echo "$filevar"(请注意双引号)。这将向echo发送一个参数,然后你可以将它传递给sed。

使用sed,这将被视为3行,因此您不需要g选项。这适用于我(bash和cygwin):

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