sdmythos_gr
sdmythos_gr

Reputation: 5654

Replace two lines in a file with one new line with bash

I am trying to replace two lines in a file with one new line:

foo1.txt
  aaa   aaa
  bbb   bbb
  ccc   ccc
  ddd   ddd
  bbb   bbb
  ddd   ddd

after the replace the file should look like this

foo1.txt
  aaa   aaa
  eee   eee
  ddd   ddd
  bbb   bbb
  ddd   ddd

Is there a way with sed or some other command make this replace in all files of a folder

I have been trying with sed but without any success: sed 's/bbb\tbbb\nccc\tccc/eee\teee/g' foo*.txt

Upvotes: 3

Views: 3247

Answers (3)

William Pursell
William Pursell

Reputation: 212584

There are a lot of ways to interpret your question. If you are trying to replace lines at a fixed position, eg lines 2 and 3, do:

sed '2d; 3s/.*/newtext/'

If you want to replace a matching line and the line following:

sed '/pattern/{ N; s/.*/newtext/; }'

To replace the two consecutive lines in which the second line matches a pattern:

sed -n '$p; N; /pattern/d; P; D'

Upvotes: 8

Avio
Avio

Reputation: 2717

Even if this question should be already answered in this thread, I didn't manage to make the "one-line-one-command" solution work.

This command:

perl -pe 's/START.*STOP/replace_string/g' file_to_change

seems not to work for me and doesn't perform a multi-line replace. I had to split it in two different perl scripts, like this:

perl -pe 's/bbb\tbbb\n.*/placeholderstring/g' foo1.txt | perl -pe 's/placeholderstring  ccc\tccc/eee\teee/g'

Try to see what works best for you.

EDIT:

With the new sample text, the only solution that works is the one by William Pursell

sed '/bbb\tbbb/{ N; s/.*ccc\tccc/  eee\teee/; }' foo1.txt

Upvotes: 1

Vijay
Vijay

Reputation: 67291

nawk '{if($0~/bbb.*bbb/){getline;getline;print "newline"};print}' your_file

tested below:

> cat temp
aaa   aaa
bbb   bbb
ccc   ccc
ddd   ddd
> nawk '{if($0~/bbb.*bbb/){getline;getline;print "newline"};print}' temp
aaa   aaa
newline
ddd   ddd

Upvotes: 1

Related Questions