user175386049
user175386049

Reputation: 499

Can i mention the backreference from different pattern to other pattern in sed

Suppose i have this data

1:a:b:c
2:d:e:f
3:a:b
4:a:b:c:d:e:f

and the output i want is

1a1b1c
2d2e2f
3a3b
4a4b4c4d4e4f

I got that from this questions

The solution which i was trying was this

sed -re 's/^([0-9]):/\1/g;s/:/L/g' temp.txt

I have two different patterns. I just want to know that can i use \1 in the second pattern

like this

sed -re 's/^([0-9]):/\1/g;s/:/\1/g' temp.txt

Upvotes: 3

Views: 176

Answers (3)

potong
potong

Reputation: 58473

This might work for you (GNU sed):

sed -r ':a;s/^(([^:]*):.*):|:/\1\2/;ta' file

Upvotes: 0

Steve
Steve

Reputation: 54512

A capture group can only be used in a substitution command it was created in. This is a great resource for learning sed: http://www.grymoire.com/Unix/Sed.html

A better way to tackle your problem, would be to use awk:

awk -F: '{ OFS=$1; $1="" }1' file

Results:

1a1b1c
2d2e2f
3a3b
4a4b4c4d4e4f

Explanation:

The -F flag sets the field separator to a colon (-F:). Then, for each line of input, set the output field separator to the first field (OFS="$1") and 'delete' the first field (or rather just set it to null; $1=""). The 1 on the end, enables default printing. HTH.

Upvotes: 5

perreal
perreal

Reputation: 98068

You can not do it that way, but there's another way to do it:

sed ':a;s/^\([0-9]*\):\([^:]*\):/\1:\2\1/;ta;s/://' input

Explanation

do {                                                           // a:
  1) match numbers at the beginning and a `:`                  // ^\([0-9]*\):
  2) match and remember everything that is not `:` upto an `:` // \([^:]*\):
  3) swap the `:` with the number from 1 (keep the first `:`)  // /\1:\2\1/
} while (there are matches)                                    // ta
finally delete the `:` after the number                        // s/://

Upvotes: 3

Related Questions