【问题标题】:End of line in shell variablesshell 变量中的行尾
【发布时间】:2011-08-03 17:34:36
【问题描述】:

所以我有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,但在那之前......

谢谢!

【问题讨论】:

  • 您接受答案然后取消了吗?这对你没有用吗?
  • @marcelog 是的。对此感到抱歉。您的回答确实有效,但我只是想看看是否还有其他选择,并决定再打开一段时间 :) 我会尽快回来查看。

标签: string shell sed


【解决方案1】:

我不明白你为什么需要将文件读入变量。你为什么不简单地这样做:

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

更新:

如果您真的想在变量中恢复 EOL。试试这个(注意引号):

echo "$filevar"

但我还是不明白,为什么你可以cat文件却不能访问文件

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

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

【讨论】:

  • 伙计..你能坚持这个话题吗?这不是因为你不明白它不应该是这样。如果是这种情况,您可以从我的问题中复制您的答案。在这种情况下,它必须以这种方式完成。对无益投反对票。
  • @filippo:请注意,我有一个类似的答案,因为从“无法直接访问文件”开始,它的含义并不清楚。
  • @ssapkota 好东西,感谢您的更新! cat 只是一个例子。这实际上是用于库中的一个函数,该函数将在许多脚本中使用。我给了$(cat testfile),因为通常是如何填充变量的。从这段代码所在的 pov 来看,$filevar 已经存在。
【解决方案2】:

改变 IFS 怎么样?

#!/bin/bash

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

这将输出:

Line one
Another line
and this is the third line

【讨论】:

    【解决方案3】:

    不要使用echo $filevar 而是使用echo "$filevar"(注意双引号)。这将向 echo 发送一个参数,然后您可以将其通过管道传递给 sed。

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

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

    【讨论】:

    • 所有其他选项都是有效选项,但我将其标记为我使用的选项。谢谢!
    【解决方案4】:

    您需要将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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-26
      • 2015-03-10
      • 2015-04-19
      • 2021-04-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多