2009-07-28 72 views
1

我試圖使用sed將文本插入文件的第一行 。我在sh 腳本中這樣做。將文本插入到shell中的Sed文件中

但爲什麼它掛在sed執行線?

#! /bin/sh 

# Command to execute 
# ./mybashcode.sh test.nbq 

nbqfile=$1 
nbqbase=$(basename $nbqfile nbq) 
taglistfiletemp="${nbqbase}taglist_temp" 
taglistfile="${nbqbase}taglist" 


./myccode $nbqfile | 
sort | 
uniq -c | 
awk '{print $2}' > $taglistfiletemp 

noftags=$(wc -l $taglistfiletemp | awk '{print $1}') 
echo $noftags 


# We want to append output of noftags 
# to the first line of taglistfile 

sed '1i\ 
$noftags' > $taglistfile 

# why it hangs here 
# the content of taglistfile is NIL 

回答

6

我不知道你正在嘗試與sed做,但它需要兩個輸入你想要的腳本(通常是查找/替換)和數據來執行它。如果您只指定一個,它會假定它已獲得正則表達式並等待stdin上的數據。因爲你沒有提供任何東西stdin它會無限期地掛起。

此外,您有'$noftags'而不是'$noftags'。之前會輸出$noftags,後面是變量的內容,因爲單引號不允許變量擴展。

+0

@MA:謝謝。的確,我錯過了sed的stdin。 – neversaint 2009-07-28 08:22:27

+1

另一個問題可能是您使用單引號而不是double,這會阻止環境變量的擴展。因此,你是literaly追加'$ noftags' – 2009-07-28 08:32:55

+0

@DJ:你說得對,謝謝。 – neversaint 2009-07-29 00:53:27

2

我在這裏有什麼問題嗎?
或者,你想要做的是在另一個文件的開頭插入一些文本?

# $NewInitialText 
# $fileToInsertInto 
echo $NewInitialText > temp.file.txt 
cat $fileToInsertInto >> temp.file.txt 
mv temp.file.txt $fileToInsertInto 

sed更容易嗎? - 雙關打算我猜。

2

它掛起,因爲你忘了提供輸入文件的sed。

.... 
... 
sed -i.bak "1i $noftags" $taglistfile 
... 
相關問題