[英]Shell Script - Read a file and add line if certain text does not exists
[英]Shell Script: how to read a text file that does not end with a newline on Windows
以下程序讀取文件,它打算將所有值(每行)存儲到變量中,但不存儲最后一行。 為什么?
file.txt :
1
2
.
.
.
n
代碼 :
FileName=file.txt
if test -f $FileName # Check if the file exists
then
while read -r line
do
fileNamesListStr="$fileNamesListStr $line"
done < $FileName
fi
echo "$fileNamesListStr" // 1 2 3 ..... n-1 (but it should print up to n.)
不是逐行閱讀,為什么不立刻讀取整個文件?
[ -f $FileName ] && fileNameListStr=$( tr '\n' ' ' < $FileName )
一個可能的原因是在最后一行n
之后錯過了換行符。
使用以下命令進行檢查:
tail -1 file.txt
以下修復:
echo >> file.txt
如果你真的需要保留最后一行沒有換行符,我while
這里重新組織了while
循環。
#!/bin/bash
FileName=0
if test -f $FileName ; then
while [ 1 ] ; do
read -r line
if [ -z $line ] ; then
break
fi
fileNamesListStr="$fileNamesListStr $line"
done < $FileName
fi
echo "$fileNamesListStr"
問題是當文件沒有以換行符結尾時,read返回非零值並且循環不會繼續。 read命令仍然會讀取數據,但不會處理循環。 這意味着您需要在循環外進行進一步處理。 您可能還需要一個數組而不是空格分隔的字符串。
文件名= file.txt的
if test -f $FileName # Check if the file exists
then
while read -r line
do
fileNamesListArr+=("$line")
done < $FileName
[[ -n $line ]] && fileNamesListArr+=("$line")
fi
echo "${fileNameListArr[@]}"
請參閱“我的文本文件已損壞!它們缺少最終的換行符!” 本文的一節: http : //mywiki.wooledge.org/BashFAQ/001
作為一種解決方法,在從文本文件中讀取之前,可以將換行符附加到文件中。
echo "\n" >> $file_path
這將確保讀取先前在文件中的所有行。 現在可以逐行讀取文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.