首页 > 解决方案 > 无法使用 bash read 命令从文件中读取行

问题描述

创建了一个文本文件为 hello_world.rtf,仅包含以下两行:Hello World

并尝试从终端使用以下 bash 脚本读取上述文件:

while test= read -r line; do
> echo "The text read from file is: $line"
> done < hello_world.rtf

它返回以下内容:

The text read from file is: {\rtf1\ansi\ansicpg1252\cocoartf1671\cocoasubrtf500
The text read from file is: {\fonttbl\f0\fswiss\fcharset0 Helvetica;}
The text read from file is: {\colortbl;\red255\green255\blue255;}
The text read from file is: {\*\expandedcolortbl;;}
The text read from file is: \paperw12240\paperh15840\margl1440\margr1440\vieww10800\viewh8400\viewkind0
The text read from file is: \pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural\partightenfactor0
The text read from file is: 
The text read from file is: \f0\fs24 \cf0 Hello\

任何建议这里有什么问题,我怎样才能得到干净的结果?

标签: bash

解决方案


RTF表示富文本格式。它是一种用于文本格式化的语言,主要由 Microsoft 开发和使用,并被弃用了一段时间。

文件中的文本与您在代码输出中看到的一样。它包含单词“Hello”“World”,还包含格式说明。

将文件另存为纯文本,而不是 RTF,它将仅包含您在其中键入的文本。

test=前面read在这个上下文中没有任何作用。你可以删除它。

确保文件的最后一行以换行符结尾。当它到达文件末尾并且您的代码退出循环并且read不显示. 如果文件以换行符结尾,则最后一行(已读取但代码未列出)为空,因此不会丢失任何内容。falsewhileread

建议文本文件始终以换行符结尾


line或者,您可以在循环后再次打印 的值。它包含文件的最后一行(从最后一个行尾字符到文件末尾)。


推荐阅读