tags:

views:

832

answers:

3

I tried to insert a text to the first line of a file using sed. I do this inside a bash script.

But why it hangs at the line of sed execution?

#! /bin/bash

# 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
+5  A: 

I'm not sure what you are trying to do with sed but it needs two inputs, the script (usually a search/replace) and the data you want to perform it on. If you only specify one it assumes it has got the regular expression and waits for data on stdin. As you haven't supplied anything on stdin it'll hang indefinitely.

In addition, you have '$noftags' rather than "$noftags". The prior will output $noftags and the latter the contents of the variable, as single quotes do not allow variable expansion.

Mike McQuaid
@MA: thanks. Indeed I missed the stdin for sed.
neversaint
another problem might be that you are using single quotes instead of double, which prevents expansion of environment variables. Thus you are literaly appending '$noftags'
Don Johe
@DJ: You are right, thanks.
neversaint
+2  A: 

Have I got something wrong here?
Or, all you want to do is insert some text at the start of another file?

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

Is that easier done than sed? -- Pun intended I guess.

nik
Loving the pun :D
Mike McQuaid
+1  A: 

it hangs because you forget to supply sed with the input file.

....
...
sed -i.bak "1i $noftags" $taglistfile 
...