[英]Read a file with a single line in bash
I am using the below code to read a file word by word in bash 我正在使用下面的代码以bash逐字读取文件
while read line; do
for word in $line; do
echo "word = '$word'"
done
done < My_File
However, the above code does not work since My_File
has only a single line. 但是,上面的代码不起作用,因为My_File
只有一行。 How should I modify the code? 我应该如何修改代码?
This reads a single line into an array, splitting on characters in IFS (by default, spaces tabs and newlines). 这会将单行读入数组,在IFS中分割字符(默认情况下,空格和换行符)。
read -r -a words <My_File || (( ${#words[@]} ))
for word in "${words[@]}"; do
echo "Read word: $word"
done
The ||
||
condition prevents set -e
(which you shouldn't be using anyhow ) from causing the script to exit if there's no terminating newline. 条件可以防止set -e
( 无论如何您都不应该使用它 )在没有终止换行符的情况下导致脚本退出。
Note that this one works only if a regular space, and no other character, separates your words. 请注意,只有当规则的空格(没有其他字符)分隔您的单词时,此选项才起作用。 If you want tabs instead, change -d ' '
to -d $'\\t'
. 如果要使用制表符,请将-d ' '
更改为-d $'\\t'
。
while IFS='' read -r -d ' ' word; word=${word%$'\n'}; [[ $word ]]; do
echo "Read word: $word"
done <My_File
word=${word%$'\\n'}
strips any newline which may be present if your file wasn't in exactly the (space-delimiter-only) format given. word=${word%$'\\n'}
删除所有换行符,如果您的文件不是完全以给定的(仅限空格分隔符)格式显示的,则可能出现换行符。
You could adjust your code like this to account for lines without a terminating newline character: 您可以像这样调整代码以说明没有终止换行符的行:
(cat My_File; echo ) | while read line; do
for word in $line; do
echo "word = '$word'"
done
done
This will add a newline at the end of the input, which won't change the output regardless of whether My_File has a newline or not. 这将在输入末尾添加换行符,无论My_File是否具有换行符,都不会更改输出。
-Rich Alloway (RogueWave) -Rich Alloway(RogueWave)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.