Reputation: 95
How could I use bash or sed to put string before and after a match? There are 4 spaces before and \n after the pattern.
Input:
Irrelevant text
line of code
Irrelevant text
Output
Irrelevant text
{code}line of code{code}
Irrelevant text
I tried
CONTENT=$(while read -r line;
do line=${line//' '/' {code}'};
line=${line//\n/'{code}'};
echo $line; done < testfile)
but it is not producing output i want.
Edit: How would I do it if I even wanted to append a different string before and different string after the pattern?
Upvotes: 0
Views: 472
Reputation: 14424
Consider using 'sed' on the whole file.
sed -e 's/ \(.*\)$/ {code}\1{code}/'
The s
operator will select the text after the spaces in group #1, and will then replace wrapped the captured group (\1
) with {code}
.
Using sed
is significantly more efficient than using bash on a line-by-line basis.
Upvotes: 1