chris
chris

Reputation: 13

Batch Sed for Windows add spaces for fixed file

I have the need to output a variable to a file, but the variable can be "example" or "example of the day" or "Exmple" in other words the variable can be any length up to 32 characters. For the file format I need the variable to always output as 32 characters with the extra characters as empty spaces.

What I'm trying to do right now is echo out the variable to a tmp file then run:

sed -i --expression="1{x;:a;/.\{32\}/!{s/^/ /;ba};x};/\(.\{32\}\).*/b;G;s//\1/;y/\n/ /" tmpfile

Which when done from the command prompt gives me exactly what I need, but when done via my batch script doesn't seem to do anything... which is odd because its not even tossing out an error, syntax issue or anything.

Once the spaces are added to the end of the variable the next question I have is when I set the file contents back to the variable:

set /p var=<tmpfile

Is the variable going to keep all of the extra spaces as needed or is going to drop them? I'll have a dozen of other variables that this will need to be done for each requiring different segment lengths which will ultimately get echoed out into a single 1000 character per line file.

At this point I'm kind of lost as to why the sed command would function exactly as expected from the command line, but fail from the batch script. I'm using GNU Sed for windows btw. Any help is very much appreciated.

Upvotes: 0

Views: 379

Answers (2)

Magoo
Magoo

Reputation: 80033

I'd suggest that certain characters in your sed command-string need to be escaped for use within a batch file. Prime candidates would be ^=|

Perhaps the easiest logical way to overcome this little quirk is to use sed's -f facility and put your sed commands in a text file

sed -fmyfile.sed filetochange.txt >changedfile.txt

where myfile.sed contains your actual sed commands.

An advantage of this approach is that you can then use exactly the same line within a batch and directly from the prompt while tinkering with the details with a text editor on the *.sed file (the .sed extension is a personal convention.)

Upvotes: 0

Aacini
Aacini

Reputation: 67216

I am afraid I don't understand your concern. However, if your question is: "How to add spaces to a variable up to a fixed length?", then this is the answer:

set var=Value shorter than 32 chars

rem Spaces:   12345678901234567890123456789012
set "var=%var%                                "
set "var=%var:~0,32%"

echo Value with fixed 32-chars length: "%var%"

Upvotes: 0

Related Questions