Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.
$ echo -e 'CH12\nCH23au' | sed '/^CH/s=^=<b>='
<b>CH12
<b>CH23au

I know I can match lines starting with CH by ^CH but how can I match multiple patterns?

Example:

Input:

CH12
CH23au

Output:

CH12
<b>CH23au

How to only put <b> where there is ^CH and au in the line?

share|improve this question

2 Answers 2

up vote 4 down vote accepted

If the CH must occur at the beginning of the line, the order of CH and au is fixed, so you can look for ^CH.*au.

$ echo -e 'CH12\nCH23au' | sed '/^CH.*au/s=^=<b>='
CH12
<b>CH23a
$

If the order of the two patterns is not fixed, one could do something like

sed -e '/pattern1/{;/pattern2/s/old/new/;}'

but the perl solution

perl -pe 'if (/pattern1/ && /pattern2/) {s/old/new/;}'

is probably more readable.

share|improve this answer

Another approach:

sed -e '/^CH/!b' -e '/au/!b' -e 's/^/<b>/'

b (branch to the end if not given any label argument) is like continue or next in other languages. So the above is like:

for (; line = readline(); print line) { # The implicit loop in sed
  if (!/^CH/) continue;
  if (!/au/) continue;
  line =~ s/^/<b>/
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.