2012-10-06 78 views
0

使用通過grep命令獲取的行號數組,我嘗試增加行號並使用sed命令檢索新行號,但是我假設了一些不對我的語法在bash腳本中使用sed

的腳本讀取(特別是中美戰略經濟對話部分,因爲一切的作品。):

#!/bin/bash 


#getting array of initial line numbers  

temp=(`egrep -o -n '\<a class\=\"feed\-video\-title title yt\-uix\-contextlink yt\-uix\-sessionlink secondary"' index.html |cut -f1 -d:`) 

new=() 

#looping through array, increasing the line number, and attempting to add the 
#sed result to a new array 

for x in ${temp[@]}; do 

((x=x+5)) 

z=sed '"${x}"q;d' index.html 

new=(${new[@]} $z) 

done 

#comparing the two arrays 

echo ${temp[@]} 
echo ${new[@]} 

回答

0

你SED線也許應該是:

z=$(sed - n "${x} { p; q }" index.html) 

請注意,我們使用「-n」標誌告訴sed只打印我們告訴它的行。當我們到達存儲在「x」變量中的行號時,它將打印它(「p」),然後退出(「q」)。爲了允許擴展x變量,我們發送給sed的逗號必須放在雙引號之間,而不是單引號。

而你應該把z變量放在雙引號之間,之後再使用它。

希望這有助於=)

+0

爲什麼要感謝你不下來投票:P – Sam

1

這可能會爲你工作:

#!/bin/bash 


#getting array of initial line numbers  

temp=(`egrep -o -n '\<a class\=\"feed\-video\-title title yt\-uix\-contextlink yt\-uix\-sessionlink secondary"' index.html |cut -f1 -d:`) 

new=() 

#looping through array, increasing the line number, and attempting to add the 
#sed result to a new array 

for x in ${temp[@]}; do 

((x=x+5)) 

z=$(sed ${x}'q;d' index.html) # surrounded sed command by $(...) 

new=("${new[@]}" "$z") # quoted variables 

done 

#comparing the two arrays 

echo "${temp[@]}" # quoted variables 
echo "${new[@]}" # quoted variables 

你sed的命令是好的;它只需要被$(...)包圍,並刪除並重新排列了不必要的引號。

BTW

要得到行模式(GNU SED)後五線:

sed '/pattern/,+5!d;//,+4d' file