Insert text into file at given line number and position

I have text that I need to insert at specific points in a file...I know the line number and position in the line.  Is there a way to do this using sed or awk or some other unix function?
kncoughlinAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

brettmjohnsonCommented:
In the past, I have used wc, head & tail to do this:
Use wc to count the lines in the original file.
Use head to take the first n lines, redirect it to a new file.
Concatenate the new content to the new file.
Use tail to take the last wc-n lines, concatenate that to the new file.

kncoughlinAuthor Commented:
Brett--Thanks for the quick response.  That works great for the line...any ideas on how I could insert at a specific postition in the line??
ozoCommented:
awk 'NR==3{$0=substr($0,1,5) "insert" substr($0,6)}{print}'

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Artysystem administratorCommented:
You don't need an awk, sed is enough in most circumstances.

Suppose you have environment variables:
LINENO=10
POSITION=5
TEXT='XXXXX'
FILE=where_to_insert

If your sed supports -E flag, this will work:

sed -E "${LINENO}s/^(.{${POSITION}})(.*)/\1${TEXT}\2/" < ${FILE}

inserts text and outputs to stdout.

Tested on FreeBSD.
Will NOT work on Solaris when native sed is used, because it doesn't support extended regular expression.

TalmashCommented:
amazing ozo !

kncoughlin, I checked ozo's command,
you just need to give AWK the parameters, like in this example :

 set LINE = 3 ; set LOC = 15 ; set TEXT = "BLABLA" ; set FILE = "file"
 awk 'NR==l{$0= substr($0,1,loc) text substr($0,loc+1)}{print}' l=$LINE loc=$LOC text=$TEXT $FILE

the parameters given to awk between the closing "'" sign to the file_name

tal
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Unix OS

From novice to tech pro — start learning today.