1

I have the following line and I want to find the field containing "ABCD" and move it just before the last field on the line.

string1;string2;xxxABCDxxx;string3;string4;string5;string6

Output

string1;string2;string3;string4;string5;xxxABCDxxx;string6
3
sed 's/\([^;]*ABCD[^;]*;\)\(.*;\)/\2\1/' <in >out

That should probably do it.

It will only work for the first occurrence of an ABCD field, though. If there are more than one on the line, all of the rest will be skipped.

To swap the last ; semicolon for a forward slash, just alter it a little:

sed 's|\([^;]*ABCD[^;]*\);\(.*;\)|\2\1/|' <in >out
  • thanks mike. it works perfect. can you help me also to get this output string1;string2;string3;string4;string5;xxxABCDxxx/string6 – Tony Jul 2 '15 at 19:00
  • it works perfect. – Tony Jul 2 '15 at 19:46
  • Sorry I didn't know that before but thank for telling me. I did pushed the buttons – Tony Jul 2 '15 at 20:32
3

If you're not tied to sed:

awk -v pattern="ABCD" '
    BEGIN { FS = OFS = ";" }
    {
        # find the first field containing the string
        for (i=1; i<NF; i++) if ($i ~ pattern) break

        # alter the last field to the desired contents
        $NF = $i "/" $NF

        # shift each subsequent field one place
        for (;i<NF; i++) $i = $(i+1)

        # reset the number of fields
        NF--

        # and output the new line
        print
    }
' filename
  • Ok, this is cool. Most of the time the awk answers are not well explained (from my perspective - I'm awk stupid). But this makes sense. Thanks. – mikeserv Jul 2 '15 at 19:21

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.