我很抱歉發佈了與我昨天工作的腳本有關的另一個問題。我的shell腳本的問題...(grep)
最初我對它有問題cd
ing帶有空格的路徑,雖然現在已經修復了。問題是,如果給腳本第三個參數,它將在它之前找到的文件中搜索它,然後打印文件位置以及找到該術語的行號。
出於某種原因grep
不喜歡路徑包含空格的文件(再次對不對?-.-),即使我有雙引號的變量我grep
ING。
有沒有人有關於如何解決它的任何想法?
#!/bin/bash
path = $1 #1st arg is the path to be searched
regex = $2 #2nd arg is a regular expression
searchTerm = $3 #3rd arg is an optional search term
startDir = `pwd` #Stores the starting path
getDirs()
{ #Function to get the directories
for i in "$1"
; do
if [ -d "$i" ]; then
echo "$i" >> temp.txt
getDirs "$i"
fi
done
}
getFiles() { # Function to get files matching the regex
while IFS= read -r path; do # While there is a line, read it, backslash is not a delimiter
cd "$path"
temp=`ls -1 | grep "$regex"` #List the contents of the dir. Store only files that match the regex
for j in $temp
do
echo "$path/$j" # For every file stored, print its location
done
cd $startDir
done < temp.txt # Read from temp.txt
}
searchFiles() { # Function to search within files
for a in $output1 # For every file found
do
out=`grep -n "$searchTerm" "$a" | cut -d: -f 1` # Find the line numbers in which it is present, stop showing after 1st :
for i in $out # For every line found
do
echo "$a: line $i" # Print the file location, and the line numbers of the terms
done
done
}
numArgs=$#
echo "$path" >> temp.txt
getDirs $path # Getting directories to search
output1=`getFiles`
cd $startDir
if [ $numArgs == 3 ] # If a search term is specified
then
searchFiles # Then search the files for it
else
echo "$output1" # Otherwise, just print the location of the files
fi
rm temp.txt # Removing temporary files
exit 0
請在此處發佈您的代碼,而不是通過鏈接。如果它看起來太長,那就是!你需要把它減少到最小的測試用例。 –
我已經添加了代碼:) –
我很確定問題是與searchFiles函數,這就是我的grep是 –