View Single Post
  #2   (View Single Post)  
Old 6th November 2010
TerryP's Avatar
TerryP TerryP is offline
Arp Constable
 
Join Date: May 2008
Location: USofA
Posts: 1,547
Default

The correct way depends on whether you want to edit the file or create a new file with the append.

If you want the same file to become

Code:
1
3 2
4
Use an ed script and invoke it from your ksh script.

Something like this should work:
Code:
Terry@vectra$ cat > testfile
1
3
4
Terry@vectra$ ed -s testfile << EOF
> 2
> a
>  2
> .
> 2,3j
> wq
> EOF
2
Terry@vectra$ cat testfile
1
3 2
4
Terry@vectra$
That ed script reads:
  1. Go to line #2
  2. Append text.
  3. ' 2' is the text to append; the single . means you're done appending.
  4. join lines 2 and 3. (Note that ed does not add or remove any whitespace on it's own!)
  5. write file and quit ed.

If you're not particularly familiar with interactive work, the '>' is my shells $PS2, used for such cases; so you don't type it in a ksh script. Like wise the << EOF thing is called a here document.

In a shell script, it would look like this:

Code:
ed -s testfile << EOF
2
a
2
.
2,3j
wq
EOF
# rest of your shell scripts code here

If you want a new file with the edits, you'll have to get a little creative with pipe lines and some of the tools for joining lines. You could also replace the ed script with an ex script, thus allowing an easier "Save as" like command to be used but the portability of ex script varies by the users competency for portability. ed scripts on the other hand are pretty darn universal.
__________________
My Journal

Thou shalt check the array bounds of all strings (indeed, all arrays), for surely where thou typest ``foo'' someone someday shall type ``supercalifragilisticexpialidocious''.
Reply With Quote