我试图让以下代码从用户那里读取变量;要搜索的文件、搜索字符串、输出所需的空格和要输出的字段数量。
第一个问题是 AWK 命令。如果我输入一个有效的空格,例如“”(单个空格)或“\t”,我会收到未终止的字符串和语法错误,只有在我请求输出多个字段时才会发生这种错误(否则不会添加空格上)。
其次,使用搜索字符串时,GREP 似乎有点挑剔。为了使用整个字符串,我必须在变量的开头和结尾添加双引号。
#!/bin/bash
#****************************************************
#Name: reportCreator.sh
#Purpose: Create reports from log files
#Author:
#Date Written: 11/01/2013
#Last Updated: 11/01/2013
#****************************************************
clear
#Determine what to search for
printf "Please enter input file name(s): "
read inputFile
printf "Please enter your search query: "
read searchQuery
printf "Please enter the whitespace character: "
IFS= read whitespace
printf "Please enter the amount of fields to be displayed: "
read fieldAmount
#Add quotation marks to whitespace and searchQuery
whitespace=\""$whitespace"\"
searchQuery=\""$searchQuery"\"
#Declare variables
declare -i counter=0
declare -a fields[$fieldAmount]
declare -a fieldInsert[$fieldAmount]
#While loop for entering fields
while [[ "$counter" -ne "$fieldAmount" ]]
do
#Ask for field numbers
printf "Please enter number for required field $((counter+1)): "
read fields[$counter]
((counter++))
done
#Create function to add '$' before every field and the whitespace characters
function fieldFunction
{
for (( counter=0; counter <= ($fieldAmount-1); counter++ ))
do
fieldInsert[$fieldAmount]="$""${fields[$counter]}"
if (( counter!=($fieldAmount-1) ))
then
printf "${fieldInsert[*]}$whitespace"
else
printf "${fieldInsert[*]}"
fi
done
}
printf "%b\n"
tac $inputFile | grep "$searchQuery" | less #| awk '{print $(fieldFunction)}'
exit 0
任何帮助,将不胜感激。