当有新行时,逐字逐句阅读的结果不同

时间:2017-03-22 17:21:47

标签: bash shell sh

我有问题,如果文件part_Q.txt在最后一条可见行之后没有新的空行,程序就无法读取文件中的所有单词。

part_Q.txt:

NWLR35MQ        649
HCDA93OW        526

*请注意,“HCDA93OW 526”行后面没有空行。文本完全在526之后完成。

当前输出:

word = 'NWLR35MQ'
word = '649'

奇怪的是,如果我在526之后再添加一行,那么我的程序会输出所有4个单词,如下所示。

预期输出:

word = 'NWLR35MQ'
word = '649'
word = 'HCDA93OW'
word = '526'

源代码:

#!/bin/sh

while read line; do    
    for word in $line; do
        echo "word = '$word'"
    done    
done < part_Q.txt

我的问题是,在526之后,如何在文件末尾没有新的空行的情况下输出所有4个单词?

1 个答案:

答案 0 :(得分:1)

您可以使用:

while IFS= read -r line || [[ -n $line ]]; do
   IFS=' '
   for word in $line; do
      echo "word=$word"
   done
done < file

word=NWLR35MQ
word=649
word=HCDA93OW
word=526

|| [[ -n $line ]] true while确保read def makeChart(dataToGraph, titleForGraph, titleYlabel, titleYlabel2, legendLabels, yMax, yMin, dataSource): fig, ax = plt.subplots() colorZ2 = ('#002060', 'red') colorZ1 = ( '#92D050', 'purple') p1 = plt.Rectangle((0, 0), 1, 1, fc='red') p2 = plt.Rectangle((0, 0), 1, 1, fc='#002060') p3 = plt.Rectangle((0, 0), 1, 0, fc='black') p4 = plt.Rectangle((0, 0), 1, 1, fc='#92D050') p5 = plt.Rectangle((0, 0), 1, 1, fc='purple') # plt.ylim(yMin, yMax) ax2 = ax.twinx() ax2 = ax.twiny() ax3 = ax.twinx() ax3 = ax.twiny() dates, series1, series2, series3, series4, series5 = zip(*dataToGraph) ax.stackplot(dates, series1, series2, colors=colorZ1) ax2.stackplot(dates, series3, series4, colors=colorZ2) ax3.plot(dates, series5, c='black', lw=3) ax2.tick_params(labeltop='off', labelright='off') # labelright is not working ax3.tick_params(labeltop='off', labelright='off') # labelright is not working # How do you turn off ticks on the right ticks? ax3.legend([p5, p4, p3, p2, p1 ], [legendLabels[4],legendLabels[3],legendLabels[2],legendLabels[1],legendLabels[0]], loc='best', shadow=True) plt.title('\n'.join(wrap(titleForGraph,50)), fontsize=14) ax.set_ylabel(titleYlabel, fontsize=14) # How do you get the label for the right to appear ax2.set_ylabel(titleYlabel2, fontsize=14) # not working ax3.set_ylabel(titleYlabel2, fontsize=14) # not working y_format = tkr.FuncFormatter(numFunc) ax.yaxis.set_major_formatter(y_format) props = dict(boxstyle='square', facecolor='none' ) fig.text(.999, 0.01, 'EPRINC', style='oblique', ha='right', fontsize=10, bbox=props) fig.text(.001, 0.01, dataSource, style='oblique', ha='left', fontsize=10, bbox=props) ax.grid(True) fig.autofmt_xdate() plt.show() def numFunc(x, pos): # formatter function takes tick label and tick position s = '{:0,d}'.format(int(x)) return s 退出状态{{1}}由于误差尾随线而失败。