tags:

views:

736

answers:

4

I need to insert string to text file, for example, before first line from the end.

STRINGS=`wc -l $OLDFILE \
    | awk '{print $1-1}' \
    | sed "s/$DOLLAR/+/g" \
    | tr -d \\\n \
    | sed "s/+$DOLLAR//" \
    | bc`
ADDFILE=$3
head -n $STRINGS $OLDFILE > $NEWFILE
cat $ADDFILE >> $NEWFILE
tail -n 1 $OLDFILE >> $NEWFILE

Can you suggest simple way to perform that? Thanks

+1  A: 
awk 'f==1{print last}{last=$0;f=1}END{print "NEW WORD\n"$0}' file
ghostdog74
Thanks, it helps
taro
+1  A: 

Maybe a bit simpler:

(tail -1 "$OLDFILE"; echo "hello there"; tac "$OLDFILE" | tail -n +2) | tac > "$NEWFILE"
Pozsár Balázs
A: 

Another (pure-bash) solution:

prev=
print=
while read line; do
    if [ "$print" ]; then
        echo $prev
    fi
    print=1
    prev="$line"
done < "$OLDFILE"
echo "hello there"
echo "$prev"
Pozsár Balázs
This is basically the same as the awk script above, but in bash.
Pozsár Balázs
+1  A: 

The most simple one:

head -n -1 "$OLDFILE"
echo "hello there"
tail -1 "$OLDFILE"
Pozsár Balázs
In my system head does not support negative offset :(,so I must calculate it myself
taro
ok, then see my other two solutions (which I deleted after posting this one, but undeleted now).
Pozsár Balázs