taro
taro

Reputation: 5832

Simple way to insert line to particular position in file

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

Upvotes: 1

Views: 6361

Answers (5)

vis.15
vis.15

Reputation: 741

The simplest one I could think of

sed -i "$ i Text to add" file.txt

Upvotes: 0

Balázs Pozsár
Balázs Pozsár

Reputation: 1689

Another (pure-bash) solution:

prev=
print=
IFS=
while read -r line; do
    if [ "$print" ]; then
        echo "$prev"
    fi
    print=1
    prev="$line"
done < "$OLDFILE"
echo "hello there"
echo "$prev"

Upvotes: 1

ghostdog74
ghostdog74

Reputation: 343107

awk 'f==1{print last}{last=$0;f=1}END{print "NEW WORD\n"$0}' file 

Upvotes: 1

Bal&#225;zs Pozs&#225;r
Bal&#225;zs Pozs&#225;r

Reputation: 1689

The most simple one:

head -n -1 "$OLDFILE"
echo "hello there"
tail -1 "$OLDFILE"

Upvotes: 1

Bal&#225;zs Pozs&#225;r
Bal&#225;zs Pozs&#225;r

Reputation: 1689

Maybe a bit simpler:

(tail -1 "$OLDFILE"; echo "hello there"; tac "$OLDFILE" | tail -n +2) | tac > "$NEWFILE"

Upvotes: 1

Related Questions