过去几个小时我一直坚持使用这个读取功能。我已经查看了Stack Overflow和在线,并且无法解决如何使用此读取功能。我可以让它在一个单独的脚本中读取文本文件,但不能使它在我当前创建的脚本中工作。
我目前正在尝试创建的脚本需要读取一个名为input.txt的文本文件,其中包含MIPS代码。它需要在一个文件中拆分正确的代码,在另一个文件中拆分错误的代码。例如。 "添加$ s0 $ s1 $ s2"将是正确的并且放入correct.txt而#34;添加$ s0 $ s1 $ z2"将是不正确的,并将其放入incorrect.txt。
# Argument names.
file=$1
correct=$2
incorrect=$3
function usageMessage() {
echo "Please enter three arguments (the input file, correct instruction output file and incorrect instruction output file)."
echo "Usage: valspit [input.txt] [correct.txt] [incorrect.txt]"
}
function readTest() {
while read -r "$file"
do
echo "$file"
done < "$1"
}
if [ $# -ne 3 ]; then
usageMessage
exit 1
fi
if [ $# -eq 3 ]; then
readTest
exit 1
fi
如果有人能告诉我如何让我的阅读功能正常工作,并告诉我如何让它逐行阅读文件,那就太棒了。
感谢。
编辑,这是输入和预期输出: input.txt:
#input.txt
add $s0 $s1 $s2
sub $s2 $t0 $t3
add $s0 $s1 $z2
lw $t1 8($t2)
addi $t3 $s0 -9
sw $s3 4($t0)
lw $t11 70000($s0)
incorrect.txt应该输出:
add $s0 $s1 $z2
lw $t11 70000($s0)
而correct.txt应该输出input.txt的其余部分
答案 0 :(得分:0)
我不知道验证MIPS代码的逻辑,但到目前为止您的代码应该是这样的。
# Argument names.
file=$1
correct=$2
incorrect=$3
function usageMessage() {
echo "Please enter three arguments (the input file, correct instruction"
echo "output file and incorrect instruction output file)."
echo "Usage: valspit [input.txt] [correct.txt] [incorrect.txt]"
}
function validate() {
string="$@"
true # not sure the logic that goes here
}
function readTest() {
local file="$1" # if we use $1 in a function, the function nees an argument
while read -r line; do # read into the variable line
if validate "$line"; then
echo "$line" >$correct
else
echo "$line" >$incorrect
fi
done <"$file" # read from file passed to us
}
if [[ $# -ne 3 ]]; then
usageMessage
exit 1 # exit 1 could have went in the function too
else # no need for two if's, an else works better
readTest $file # there was no reason to exit as a failure here
fi