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?
 
ozoCommented:
awk 'NR==3{$0=substr($0,1,5) "insert" substr($0,6)}{print}'
0
 
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.

0
 
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??
0
 
NopiusCommented:
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.

0
 
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
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.