0

I have a large file with strings like "xyz.abc.001.xxx.0.820" and I want to replace it with "0,820,xyz.abc.001.xxx" in total file.

Examples:

xyz.abc.001.xxx.0.820\ to 0,820,xyz.abc.001.xxx 
xyz.abc.001.xxx.820.123\ to 820,123,xyz.abc.001.xxx
xyz.abc.001.xxx.1000.2000\ to 1000,2000,xyz.abc.001.xxx 
xyz.abc.001.xxx.1.100\ to 1,100,xyz.abc.001.xxx 

I am using below sed command with regular expression but not replacing correctly

sed -E "s/(xyz.abc[0-9]\+\.xxx)\.([0-9]\+)\.([0-9]\+)\\/\2,\3,\1/g" file_name

Is it possible do like this?

Thanks in Advance.

3
  • Welcome to the site. Your post is not entirely clear, e.g. you have 0:820 in your first output example, but comma-separation for the first two fields in the rest; is that a typo? Is it correct to say that you want to prepend the strings with the last two .-separated fields, but comma-separated? What about the \ , is that really there? Does it need to be sed, or is awk a valid alternative? – AdminBee Jun 15 '20 at 12:18
  • we all asume :820 is a typo and should be ,820 (comma 820), is this right ? – Archemar Jun 15 '20 at 12:42
  • @Archemar yes that's right, it should be ,820 (comma 820). I updated the question. – Naren Jun 15 '20 at 12:47
1

try either

sed -E "s/(xyz.abc.*xxx).([0-9]+)\.([0-9]+)./\2,\3,\1/" 
sed -E "s/(xyz.abc.*xxx).([0-9]+)\.([0-9]+)\\\\/\2,\3,\1/" 

where

  • pattern select is done by \( ... \)
  • trailling \ can be caught either by . (any char), or \\\\ (escape from shell and escape from sed)
  • note I use either . or \. to specify a dot
0

Can't try it right now, but it doesn't look too wrong to me. \+ is out of standard, so try

sed -E "s/(xyz\.abc[0-9]{1,}\.xxx)\.([0-9]{1,})\.([0-9]{1,})\\/\2:\3,\1/g" file_name
0

If it doesn't have to be sed, you can try the following awk-based solution:

awk -F. -v OFS="." '{sub(/\\$/,"",$NF); printf("%s,%s,",$NF,$(NF-1)); NF=NF-2}1' input.txt

This will interpret each line as .-separated fields, strip the trailing \ from the last, and print the last two fields comma-sepated at the beginning of the output line, followed by remaining fields (again .-separated).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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