user2809888
user2809888

Reputation:

How to insert a text in middle of nth line of file

I am trying to insert a pipe symbol in between nth line of a file. Like the one present in the output of diff command.

Do not want to use VI editor.

For example,desired line is 2nd line of the file:

cat filename

Hi            Hi
Hello         Hello
This          This
is            Is
it            it

desired output:

cat filename

Hi            Hi
Hello    |     Hello
This          This
is            Is
it            it

Upvotes: 0

Views: 1708

Answers (3)

Ed Morton
Ed Morton

Reputation: 204731

For your own sanity, just use awk:

$ awk 'NR==2{mid=length($0)/2; $0=substr($0,1,mid) "|" substr($0,mid+1)} 1' file
Hi            Hi
Hello    |     Hello
This          This
is            Is
it            it

To modify the original file you can add > tmp && mv tmp file or use -i inplace if you have GNU awk.

Upvotes: 1

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed '
# select 2nd line
/2/ {
# keep original in memory
   G;h
:divide
# cycle by taking the 2 char at the egde of string (still string end by the \n here) and copy only first to other part of the separator (\n)
   s/\(.\)\(.*\)\(.\)\(\n.*\)/\2\4\1/
# still possible, do it again
   t divide
# add last single char if any and remove separator
   s/\(.*\)\n\(.*\)/\2\1/
# add original string (with a new line between)
   G
# take first half string and end of second string, and place a pipe in the middle in place of other char
   s/\(.*\)\n\1\(.*\)/\1|\2/
   }' YourFile
  • posix sed, so --POSIXfor GNU sed
  • Sel explain

Upvotes: 0

You basically cannot modify in place some textual file by inserting a character inside a line. You need to read all its content, modify that content in memory, then write the new content.

You might be interested in GNU ed, which can edit a file programmatically (inside some script).

You could use awk (or any other filter) and redirect its output to some temporary file, then rename that temporary file as the original one.

Upvotes: 1

Related Questions