【问题标题】:Reading file line by line (with space) in Unix Shell scripting - Issue在 Unix Shell 脚本中逐行(带空格)读取文件 - 问题
【发布时间】:2013-05-23 07:30:39
【问题描述】:

我想在 Unix shell 脚本中逐行读取文件。行可以包含前导和尾随空格,我也想在行中读取这些空格。 我尝试使用“同时读取行”,但读取命令正在从行中删除空格字符:( 例如,如果文件中的行是:-

abcd efghijk
 abcdefg hijk

行应读作:- 1) "abcd efghijk" 2) " abcdefg hijk"

我试过的是这个(没用):-

while read line
do
   echo $line
done < file.txt

我想要包含空格和制表符的行。 请提出一种方法。

【问题讨论】:

    标签: shell unix ksh


    【解决方案1】:

    试试这个,

    IFS=''
    while read line
    do
        echo $line
    done < file.txt
    

    编辑:

    来自man bash

    IFS - The Internal Field Separator that is used for word
    splitting after expansion and to split lines into words
    with  the  read  builtin  command. The default value is
    ``<space><tab><newline>''
    

    【讨论】:

    • 惯用语,您将只为 read 语句指定空的 IFS,以避免奇怪的副作用:while IFS= read line
    【解决方案2】:

    您想阅读 raw 行以避免输入中的反斜杠出现问题(使用 -r):

    while read -r line; do
       printf "<%s>\n" "$line"
    done < file.txt
    

    这将保留行内的空格,但会删除前导和尾随空格。要保留这些,请将 IFS 设置为空,如

    while IFS= read -r line; do
       printf "%s\n" "$line"
    done < file.txt
    

    这相当于cat &lt; file.txt,只要file.txt 以换行符结尾。

    请注意,您必须双引号 "$line" 以防止分词将行拆分为单独的词 - 从而丢失多个空格序列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-22
      • 1970-01-01
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 2012-06-03
      相关资源
      最近更新 更多