Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding and replacing lines that begin with a pattern

Tags:

regex

unix

sed

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
like image 467
Ank Avatar asked Jul 25 '12 23:07

Ank


People also ask

How do you replace some text pattern with another text pattern in a file?

`sed` command is one of the ways to do replacement task. This command can be used to replace text in a string or a file by using a different pattern.

How do you find and replace a pattern in Unix?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.


3 Answers

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
like image 84
jahroy Avatar answered Sep 23 '22 17:09

jahroy


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
like image 42
Mark Wilkins Avatar answered Sep 19 '22 17:09

Mark Wilkins


With awk

awk '/^a\tb/{$0="REPLACED TEXT"} 1' foo.txt
like image 27
slitvinov Avatar answered Sep 23 '22 17:09

slitvinov