jimjamz
jimjamz

Reputation: 69

Reversing results in a file using sed

I have a file called sum.txt, which contains the following line:

ccc7b3c6501338da68d0484d204994d82bbd9487 ?SHA1*myTest.feature=

If I do this:

sed -E 's/^.* \?/rabbit/' sum.txt > sum2.txt

In sum2.txt, it gives me this:

rabbitSHA1*myTest.feature

then this:

sed -E 's/SHA1\*.*$/\dog/' sum2.txt > sum3.txt

in sum3.txt gives me this:

rabbitdog

Therefore, I know my regular expressions work correctly on the original line of text in sum.txt.

Objective: What I really want to do, is to take these two pieces of the line and swap them around in the original text file, so sum.txt would look like:

SHA1*myTest.feature=ccc7b3c6501338da68d0484d204994d82bbd9487 ?

I tried using sed's placeholders (\2 and \1) to swap the order in which they appear in the file:

sed -E 's/\(^.* \?\)\(SHA1\*.*$\)/\2\1/' sum.txt > sum2.txt or

sed 's/\(^.* ?\)\(SHA1\*.*$\)/\2\1/' sum.txt > sum2.txt

but it doesn’t work. The result I am getting is this:

ccc7b3c6501338da68d0484d204994d82bbd9487 ?

Question: What am I doing wrong and should I be using AWK to achieve this instead?

Addendum: The above file I have used in this use-case scenario is one of many sum.txt files. Each sum.txt file resides in a different sub-directory along with the file that appears in the sum.txt. Therefore, each sum.txt has a unique hash string and different .feature filename, sometimes even with a different file extension other than .feature. For example, another sum.txt file that appears in a different sub-directory could look something like:

2e1843ec8330588789790e86c72fd39903335608 ?SHA1*yetAnother.test=

The ultimate goal is to use the sed command within a For Files recursive loop that goes through each sub-directory and modifies many sum.txt files.

Upvotes: 1

Views: 90

Answers (2)

Ed Morton
Ed Morton

Reputation: 203229

$ sed 's/\(.*?\)\(.*\)/\2\1/' file
SHA1*myTest.feature=ccc7b3c6501338da68d0484d204994d82bbd9487 ?

$ awk -F'?' '{print $2 $1 FS}' file
SHA1*myTest.feature=ccc7b3c6501338da68d0484d204994d82bbd9487 ?

Upvotes: 0

heemayl
heemayl

Reputation: 41987

You can match till ? as captured group 1, and the rest in group 2, and then swap them around in replacement:

sed -E 's/^([^?]+\?)(.*)/\2\1/' sum.txt

Example:

$ sed -E 's/^([^?]+\?)(.*)/\2\1/' <<<'ccc7b3c6501338da68d0484d204994d82bbd9487 ?SHA1*myTest.feature='
SHA1*myTest.feature=ccc7b3c6501338da68d0484d204994d82bbd9487 ?

Upvotes: 1

Related Questions