Click to See Complete Forum and Search --> : Copy pattern found multiple times on the same line using sed.
709394
12-06-2007, 11:59 AM
Is it possible to copy pattern found multiple times on the same line using sed?
In my case, I want to copy the coloring code(#......;) multiple times and at the same time append ++ to coloring code.
Example:
Input:
85 : color: #5895be;
93 : background: #5294c1;
170 : border-bottom: 2px solid #d3e7f4;
Wanted output:
++#5895be;85 : color: #5895be; ++#5895be;
++#5294c1;93 : background: #5294c1; ++#5294c1;
++#d3e7f4;170 : border-bottom: 2px solid #d3e7f4; ++#d3e7f4;
hotcold
12-06-2007, 07:09 PM
Hi.
The sed substitute command can do this:
#!/usr/bin/env sh
# @(#) s1 Demonstrate sed string capture and insert operators.
set -o nounset
echo
debug=":"
debug="echo"
## Use local command version for the commands in this demonstration.
echo "(Versions displayed with local utility \"version\")"
version >/dev/null 2>&1 && version bash sed
echo
FILE=${1-data1}
echo " Input file:"
cat $FILE
echo
echo " Desired results:"
cat desired-results
echo
echo " Results from sed:"
sed -e 's_^\(.*\)\(#.*;\)\(.*\)$_++\2\1\2\3\ ++\2_' $FILE
exit 0
Producing:
% ./s1
(Versions displayed with local utility "version")
GNU bash 2.05b.0
GNU sed version 4.1.2
Input file:
85 : color: #5895be;
93 : background: #5294c1;
170 : border-bottom: 2px solid #d3e7f4;
Desired results:
++#5895be;85 : color: #5895be; ++#5895be;
++#5294c1;93 : background: #5294c1; ++#5294c1;
++#d3e7f4;170 : border-bottom: 2px solid #d3e7f4; ++#d3e7f4;
Results from sed:
++#5895be;85 : color: #5895be; ++#5895be;
++#5294c1;93 : background: #5294c1; ++#5294c1;
++#d3e7f4;170 : border-bottom: 2px solid #d3e7f4; ++#d3e7f4;
Best wishes ... cheers, hotcold
709394
12-07-2007, 04:33 PM
Thx Hotcold for the solution.
To answer my own question. To use the pattern(regex) defined in left hand side, you have to put your pattern(regex) inside brackets and then call the pattern(regex) found on the right hand side by using \X, where X is the pattern(regex) grouped inside brackets.
Example:
sed -e 's/(1stPartRegex)(2ndPartRegex)(XthPartRegex)/ \1 \2 \X/' ....
Here is the link that help me understand what Hotcold wrote:
http://www.grymoire.com/Unix/Sed.html#uh-4