How to append text to the second line of a file

Say I have a text file like:

1
3
4

How would I use ksh to put the number '2' into the second line of that file? I'm using OpenBSD so the sed syntax might be a bit different (I have no idea how to use sed, though)

Hi,

Here a 'sed' script. I don't know if it could work under a BSD. My machine is a Linux one.

$ cat infile
1
3
4
$ cat script.sed
2 i\
2
$ sed -f script.sed infile
1                                                                                                                                                                                                                 
2                                                                                                                                                                                                                 
3                                                                                                                                                                                                                 
4

Regards,
Birei

1 Like

In my opinion, this is a job for awk rather than sed.

Assuming that tokens are numeric, and are always column one, then:

#!/usr/bin/env ksh
awk '
        {
                if( last )
                        for( i = last + 1; i < $1+0; i++ )
                                printf( "%d\n", i );
                last = $1+0;
                printf( "%s\n", $0 );
        }
' <input-file >output-file

Purely in Ksh:

#!/usr/bin/env ksh

last=0
while read x junk
do
        for (( i=$(( $last + 1 )); i < $x; i++ ))
        do
                printf "%d\n" $i
        done

        last=$x
        print $x $junk
done <input >output

(Read allows for more than one token on the line, hence the junk variable)

---------- Post updated at 19:18 ---------- Previous update was at 19:17 ----------

Of course birei beat me with a sed example :wink:

1 Like
awk 'NR==2{$0="2" RS $0}1' infile
sed '2s/^/2\n/' infile

---------- Post updated at 09:18 ---------- Previous update was at 09:07 ----------

ksh:

#!/bin/ksh
while read -r line; do
  if (( ++i == 2 )); then
    echo 2
  fi
  printf "%s\n" "$line"
done < infile