我第一次尝试使用Bourne shell脚本,我似乎无法确定如何将文件从文件保存到内部脚本变量。文件格式如下:
acc.text
Jason Bourne 213.4
Alice Deweger 1
Mark Harrington 312
我拥有的当前脚本(可能完全不正确,因为我只是在NotePad ++中创建它而不使用实际的shell控制台)如下所示:
#!/bin/sh
process_file()
{
FILE = $1;
SALARYARRAY;
NAMEARRAY;
COUNTER = 0;
while read line
do
$NAMEARRAY[$COUNTER] =
$SALARYARRAY[$COUNTER] =
$COUNTER + 1;
echo $NAMEARRAY[$COUNTER]:$SALARYARRAY[$COUNTER];
done < "$FILE"
order_Map
}
# Function is not complete as of now, will later order SALARYARRAY in descending order
order_Map()
{
i = 0;
for i in $COUNTER
do
if ($SALARYARRAY[
done
}
##
# Main Script Body
#
# Takes a filename input by user, passes to process_file()
##
PROGRAMTITLE = "Account Processing Shell Script (APS)"
FILENAME = "acc.$$"
echo $PROGRAMTITLE
echo Please specify filename for processing
read $FILENAME
while(! -f $FILE || ! -r $FILE)
do
echo Error while attempting to write to file. Please specify file for processing:
read $FILENAME
done
echo Processing the file...
process_file $FILENAME
答案 0 :(得分:2)
我修复了你的一些脚本。在将它们存储到数组之前,您需要cut
出每行的名称和工资字段。
#!/bin/bash
process_file()
{
file=$1;
counter=0
while read line
do
#the name is the first two fields
name=`echo $line | cut -d' ' -f1,2`
NAMEARRAY[$counter]="$name"
#the salary is the third field
salary=`echo $line | cut -d' ' -f3`
SALARYARRAY[$counter]="$salary"
echo ${NAMEARRAY[$counter]}:${SALARYARRAY[$counter]}
counter=$(($counter+1))
done < $file
}
##
# Main Script Body
#
# Takes a filename input by user, passes to process_file()
##
PROGRAMTITLE="Account Processing Shell Script (APS)"
echo $PROGRAMTITLE
echo -n "Please specify filename for processing: "
read FILENAME
if [ -r $FILENAME ] #check that the file exists and is readable
then
process_file $FILENAME
else
echo "Error reading file $FILENAME"
fi
答案 1 :(得分:0)
根据您指定的文件格式,每条记录最后有三个字段,最后是金额,然后是:
i=0
while read fistname lastname amount; do
NAMEARRAY[$i]="$firstname $lastname"
SALARYARRAY[$i]=$amount
i = `expr $i + 1`
done < "$FILE"
shell内置读取,自动拆分输入。请参见手册页中sh(1)的变量IFS。如果您在金额字段后面有数据,并且您希望忽略它,只需在金额后创建另一个变量;但不要使用它。它会将前3个字段之后的所有内容收集到额外变量中。
你指定了Bourne shell,所以我使用了一些非常陈旧的东西:
i=`expr $x + 1`
通常是写的
let $((i++)) # ksh, bash (POSIX, Solaris, Linux)
在现代系统上,/ bin / sh通常是ksh或非常兼容的东西。您可以使用let $((i++))