We help IT Professionals succeed at work.

Insert text into file at given line number and position

kncoughlin
kncoughlin asked
on
Medium Priority
6,486 Views
Last Modified: 2008-01-09
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?
Comment
Watch Question

Top Expert 2005

Commented:
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.

Author

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??
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015
Commented:
awk 'NR==3{$0=substr($0,1,5) "insert" substr($0,6)}{print}'

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Artysystem administrator
Top Expert 2007

Commented:
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.

TalmashCEO

Commented:
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
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.