2009-07-28 74 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 
... 
相关问题