0

I'm on Windows 7. I have a large text file code.txt with the following equalities

        oReservist.Role = Sheets("RECAP").Cells(ligne, 2)
        oReservist.Surname = Sheets("RECAP").Cells(ligne, 3)
        oReservist.Name = Sheets("RECAP").Cells(ligne, 4)
        ...

I want to change the first part of the equality by the second and the second by the first one. That is to say :

        Sheets("RECAP").Cells(ligne, 2) = oReservist.Role
        Sheets("RECAP").Cells(ligne, 3) = oReservist.Surname
        Sheets("RECAP").Cells(ligne, 4) = oReservist.Name 
        ...

How can I handle that ?

Until now that if I were on Linux I could have used awk with " = " as field separator, and simply turn around the fields.

awk -F " = " '{OFS=FS;print $2,$1}' file

or using sed:

sed 's/\(.*\) = \(.*\)/\2 = \1/' file

But it seems they are not recognised on Windows as I have the folowing error:

 PS C:\Users\alliasjb\Desktop> sed
Le terme « sed » n'est pas reconnu comme nom d'applet de commande, fonction, fichier de script ou programme exécutable.
 Vérifiez l'orthographe du nom, ou si un chemin d'accès existe, vérifiez que le chemin d'accès est correct et réessayez
2
  • Why are you asking for both linux and windows? If the sed solution doesn't work on windows, which seems to be your OS of choice, then remove the linux and sed tags. Jun 24, 2019 at 14:33
  • If you are used to UNIX commands and find yourself working on Windows, then Cygwin, Cmder or WSL (on Windows 10) are going to give you much solace. There you may awk, sed or perl -pe 's/(.*) = (.*)/$2 = $1/' file.
    – simlev
    Jun 25, 2019 at 8:16

3 Answers 3

1

A powershell solution:

  • working on all platforms
  • keeping a possible indentation

(Get-Content .\code.txt) -replace '(\s*)(.*)( = )(.*)','$1$4$3$2'

To save to a(nother) file append

| Set-Content .\newcode.txt
0

You can download Gawk for Windows and sed for Windows.

I only tested sed in the Win10 command prompt:

C:\bin>more test.txt
oReservist.Role = Sheets("RECAP").Cells(ligne, 2)
oReservist.Surname = Sheets("RECAP").Cells(ligne, 3)
oReservist.Name = Sheets("RECAP").Cells(ligne, 4)

C:\bin>sed.exe "s/\(.*\) = \(.*\)/\2 = \1/" test.txt
Sheets("RECAP").Cells(ligne, 2) = oReservist.Role
Sheets("RECAP").Cells(ligne, 3) = oReservist.Surname
Sheets("RECAP").Cells(ligne, 4) = oReservist.Name
0

Another PowerShell way:

Import-Csv .\code.txt -Delimiter '=' -Header 'Left', 'Right' |
   %{ $_.Right + ' = ' + $_.Left } | out-file .\newcode.txt

If you need to presevere indentation, just modify the ForEach (%) block: { ' ' + $_.Right + ' = ' + $_.Left }

Keith

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .