Bash 如何读取命名文件?
我正在尝试将输入文件中的所有行复制到另一个文件:Bash 如何读取命名文件?,bash,file-io,Bash,File Io,我正在尝试将输入文件中的所有行复制到另一个文件: #!/bin/bash in=$1 file="current_line.txt" let count=0 echo $count while read LINE do (( count++ )) echo $count echo $LINE > $file done 为什么read命令不能从我作为脚本参数提供的文件中获取输入?#/bin/bash #!/bin/bash in=$1 fi
#!/bin/bash
in=$1
file="current_line.txt"
let count=0
echo $count
while read LINE
do
(( count++ ))
echo $count
echo $LINE > $file
done
为什么read
命令不能从我作为脚本参数提供的文件中获取输入?#/bin/bash
#!/bin/bash
in=$1
file="current_line.txt"
count=0
echo $count
while read -r LINE
do
echo $LINE >> $file
count=$((count + 1))
echo $count
done < "$in"
英寸=1美元
file=“current_line.txt”
计数=0
echo$count
而read-r行
做
echo$LINE>>$file
计数=$((计数+1))
echo$count
完成<“$in”
在输入文件末尾按上述方式提供输入文件。虽然您在变量中设置了
以指向您的输入文件,但尚未对其执行任何操作。内置的read
将从其标准输入中读取,该输入将被继承,因此,如果它在任何时候都没有重定向,则会一直返回到调用它的终端(或终端仿真器)shell会话
可以在调用脚本时重定向脚本的标准输入,也可以通过
exec <"$in"
while read LINE
do
# ...
done
另一种选择是为输入指定一个文件描述符,并使用read-u
将其用于read
命令:
exec 3<"$in"
while read -u 3 LINE
do
# ...
done <"$in"
exec 3<&- # to close the file neatly
还要注意,每个echo$行
都将覆盖$文件
,因此您只能在脚本完成时看到输入的最后一行。考虑重定向输入的同时重定向整个<代码>的输出,而<代码>循环与重定向输入的方式相同,如果这不是你想要的。例如:
while read LINE
do
# ...
echo "$LINE" # Note the quoting (unless you actually intend to collapse whitespace)
done <"$in" >"$file" # and here!
读取行时
做
# ...
回显“$LINE”#注意引号(除非你真的打算折叠空格)
完成“$file”#这里!
您从哪里阅读?您正在使用
重定向,它将创建一个新文件current\u file.txt
,内容为$LINE
。如果您想在文件中累积行数,请使用>
而不是
。好的,当我在读取行数时使用,行数不会从“in”中读取行数,其中in具有包含文本的文件名,您告诉它从“in”中读取行数的位置是什么?您可能已为“in”设置了值,但没有任何内容指示重定向到文件循环;)我怎样才能告诉while读取“in”表中的行呢?@LRobert我已经检查过它在我的系统上运行。如果您有任何疑问,请告诉我。感谢您解释详细信息:)
exec 3<"$in"
while read -u 3 LINE
do
# ...
done <"$in"
exec 3<&- # to close the file neatly
in="$1"
while read LINE
do
# ...
echo "$LINE" # Note the quoting (unless you actually intend to collapse whitespace)
done <"$in" >"$file" # and here!