Max
Max

Reputation: 153

How to append a character at the end of a specific line in a loop?

I want to read line numbers from a file and according to that insert characters in another file. This is what I got so far:

#!/bin/bash

character=:
line_number=1
sed $line_number's/$/ '$character'/' <readme >readme_new
line_number=3
sed $line_number's/$/ '$character'/' <readme_new >readme_newer

I would like to do that in a loop now.

Upvotes: 0

Views: 343

Answers (1)

Paul Hodges
Paul Hodges

Reputation: 15313

TL;DR:

$: c='!'
$: sed "s#\$# s/\$/ $c/#" fibs >script
$: sed -i "$(<script)" infile

Broken out -

A file of line numbers:

$: cat fibs
1
2
3
5
8
13
21

a file to be edited:

$: cat infile
  1 a
  2 b
  3 c
  4 d
  5 e
  6 f
  7 g
  8 h
  9 i
 10 j
 11 k
 12 l
 13 m
 14 n
 15 o
 16 p
 17 q
 18 r
 19 s
 20 t
 21 u
 22 v
 23 q
 24 x
 25 y
 26 z

3 steps -- first set your character variable if you're using one.

$: c='!'

Then make a script from the line number file -

$: sed "s#\$# s/\$/ $c/#" fibs >script

which creates:

$: cat script
1 s/$/ !/
2 s/$/ !/
3 s/$/ !/
5 s/$/ !/
8 s/$/ !/
13 s/$/ !/
21 s/$/ !/

It's a simple sed to add a sed substitution command for each line number, and sends the resulting script to a file. A few tricks here include using double-quotes to allow the character embedding, and #'s to allow the replacement text to include /'s without creating leaning-toothpick syndrome from all the backslash quoting.

Then run it against your input -

$: sed -i "$(<script)" infile

Which does the work. That pulls the script file contents in for sed to use, generating:

  1 a !
  2 b !
  3 c !
  4 d
  5 e !
  6 f
  7 g
  8 h !
  9 i
 10 j
 11 k
 12 l
 13 m !
 14 n
 15 o
 16 p
 17 q
 18 r
 19 s
 20 t
 21 u !
 22 v
 23 q
 24 x
 25 y
 26 z

Let me know if you want to tweak it.

Upvotes: 2

Related Questions