Issue
I have a file such as
1,ab012a800,20141205
2,ab023a801,20141205
3,ab012a802,20141205
1,ab024a803,20141205
1,ab012a804,20141205
I want to extract the 'ab012a' part and append that to the end of the line.
1,ab012a800,20141205,ab012a
2,ab023a801,20141205,ab023a
3,ab012a802,20141205,ab012a
1,ab024a803,20141205,ab024a
1,ab012a804,20141205,ab012a
I can extract with grep :
grep -o '^[a-z][a-z][0-9]*[a-z]' file
and append to a line with sed :
sed "s/$/,whatever/"
or even replace the pattern with sed :
sed '/^[a-z][a-z][0-9]*[a-z]/ s/$/something/' file
but how would I append the matching pattern to the end of the line?
Many thanks
Solution
You can use:
sed -i.bak 's/\(,[a-z][a-z][0-9]*[a-z]\).*$/&\1/' file
1,ab012a800,20141205,ab012a
2,ab023a801,20141205,ab023a
3,ab012a802,20141205,ab012a
1,ab024a803,20141205,ab024a
1,ab012a804,20141205,ab012a
&
is special symbol in replacement that represents full matched string by regex used and \1
represents the matched group #1.
Answered By - anubhava