我想要獲取以下代碼來讀取用戶的變量;要搜索的文件,搜索字符串,需要輸出的空白以及要輸出的字段數量。未終止的字符串/語法錯誤與Bash
第一個問題是使用AWK命令。如果我輸入一個有效的空格,例如「」(單個空格「或」\ t「),我會得到未終止的字符串和語法錯誤,這隻有在請求輸出多個字段時纔會發生(否則不會添加空格) on)。
其次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
任何幫助,將不勝感激。
謝謝!我不敢相信這是多麼容易。最初我將引號添加到$ searchQuery是因爲我試圖弄清楚爲什麼它不起作用時收到的錯誤。 我早些時候也厭倦了AWK的雙引號,但我想我一定已經改變了他們回去試圖解決問題。 再次感謝! :) – Revenant
你永遠不需要grep with awk,你永遠不應該在你的awk腳本中使用雙引號。你的根本錯誤是使用shell腳本來創建你想讓你的awk腳本使用的字段列表和格式 - 只需在awk腳本中做到這一點,所有的卷積就消失了。 –