• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 6463
  • Last Modified:

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

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now