9

I have a text in a file file.txt like this

xxxxxxxxxxxxxxx
xxxxxxxxxxxxxxx
a    b   c // delimited by tab
xxxxxxxxxxxxxxx
xxxxxxxxxxxxxxx

I know using sed I can find and replace text in a file. If a line starts with a b(seperated by a tab) I need to replace it with d e f. So the above file will be

xxxxxxxxxxxxxxx
xxxxxxxxxxxxxxx
d    e   f // delimited by tab
xxxxxxxxxxxxxxx
xxxxxxxxxxxxxxx

I can do this to find and replace, I want only those instances where the line starts with a b and replace the whole line.

sed -i 's/a/\t/\b/\t\/c/REPLACED TEXT/g' file.TXT
jahroy
  • 22,322
  • 9
  • 59
  • 108
Ank
  • 6,040
  • 22
  • 67
  • 100

4 Answers4

30

Use a ^ symbol to represent the beginning of a line:

sed -i 's/^a\tb.*$/REPLACED TEXT/g' file.TXT

Exmplanation:

  • ^ means beginning of line/input
  • \t means tab symbol
  • . means any character
  • * means zero or more of the preceeding expression
  • $ means end of line/input
jahroy
  • 22,322
  • 9
  • 59
  • 108
1

The following will replace the entire line if it begins with a<tab>b<tab>c. The .*$ makes the match include the entire line for replacement. Your example regex included c but the prose only mentioned a and b, so it wasn't quite clear if c is required. If not, then remove \tc from the regex.

s/^a\tb\tc.*$/REPLACED TEXT/g
Mark Wilkins
  • 40,729
  • 5
  • 57
  • 110
1

With awk

awk '/^a\tb/{$0="REPLACED TEXT"} 1' foo.txt
slitvinov
  • 5,693
  • 20
  • 31
0

This might work for you (GNU sed):

sed -i '/^a\tb/c\replacement text' file
potong
  • 55,640
  • 6
  • 51
  • 83