prabodhprakash
prabodhprakash

Reputation: 3917

insert text at nth offset from start in command line

I've a file in which I get offset from starting position where I need to insert some text. For e.g. if the file looks like below

Hello World
How are you doing today?
I'm good. Thanks for asking.

I may get input like 3, 10, 25 offset from start where I've to insert text.

Is there a command-line way to do it? I have tried using sed but, it works line by line and does not honor offset from start. This is what I wrote for sed

sed 's/./&\
 inserted text\
   /25' in.txt > out.txt

What above does is - for every line, at 25th character, it inserts inserted text - but, I want it to be done at 25th offset from starting position of the file.

Upvotes: 1

Views: 246

Answers (1)

anubhava
anubhava

Reputation: 785058

One way to do this is by using a control character RS in awk. This makes whole file a single record for awk:

awk -v RS='\07' -v p=25 -v t='inserted text' '{
      print substr($0, 1, p) t substr($0, p+1)}' ORS= file

Hello World
How are you dinserted textoing today?
I'm good. Thanks for asking.

Upvotes: 1

Related Questions