Sunny
Sunny

Reputation: 103

Swapping mupltiple words and numbers that occur in one line using SED

I have a large file where in every line it shows :

OCCUPY 12 EVERY PIC 32(12) 
OCCUPY 45 EVERY PIC X(21) 
OCCUPY 98 EVERY PIC F(A0)
OCCUPY 21 EVERY PIC T(BC)

And desired output should be :

PIC 32(12) OCCUPY 12 EVERY 
PIC X(21) OCCUPY 45 EVERY
PIC F(A0) OCCUPY 98 EVERY

and so on.

So, this is just an example, but in the file there are lots of lines with different chars/numbers near PIC and different numbers near OCCUPY.

So far, I tried executing :

sed -E 's/(.*OCCUPY\ )(0([A-Z]\([0-9])\)(.*EVERY\ )(.*PIC\ )(([0-9]\([0-9]+\))/\3\4\1\2/'
sed -E 's/((OCCUPY )([A-Z]\([0-9]))\)(.*EVERY )(.*PIC)(([0-9]\([0-9]))/\3\4\1\2/'

But, it didn't help .

I would appreciate any help!

Upvotes: 2

Views: 66

Answers (2)

xhienne
xhienne

Reputation: 6144

Judging by your sample, your sed command seems too complicated. What about this simpler version?

sed 's/\(.*\) \(PIC .*\)/\2 \1/'

[update] Your lines are more complicated than stated in your post. They are like:

MS-MSG OCCUPY 12 EVERY PIC 32(12) 0012345

And you want:

PIC 32(12) OCCUPY 12 EVERY

Then, all you have to do is add those extra characters to the left-side of the substitution command, but outside the parentheses (whose content is used to build the new string):

sed 's/.* \(OCCUPY .*\) \(PIC [^ ]*\).*/\2 \1/'

Upvotes: 5

user7712945
user7712945

Reputation:

if your data in d file, tried on gnu sed:

sed -E 's/^(OCCUPY.+EVERY).+(PIC \S+)/\2 \1/' d 

Upvotes: 1

Related Questions