-2

I'm trying to tidy up some code. Right now I have:

SET VAR=%TIME:.=&rem.%
SET VAR=%VAR:,=&rem.%
SET VAR=%VAR::=_%

And it works, but I wuld like to turn it into one-liner. Something like this (doesn't work):

SET VAR=% % %TIME:.=&rem% :,=&rem.% ::=_%

Can I achieve something like this with concise, simple syntax?

franiis
  • 1,378
  • 1
  • 18
  • 33
  • 2
    why not just chain them using `&&` like `set something && set another &&...` – Gerhard Nov 14 '18 at 08:32
  • I don't want obfuscate code. I would like to have readable one line setting for each variable. That's why I'm looking for some shortened (yet readable) syntax. Maybe like `SET VAR = %.. :... :... :...%` or nesting. I don't see anything similar (possibly doesn't exist, but I'm not an expert). – franiis Nov 14 '18 at 08:43
  • 1
    you seemed to have missed my comment.. `set VAR=%TIME:.=&rem.% && set VAR=%VAR:,=&rem.% && set VAR=%VAR::=_%` – Gerhard Nov 14 '18 at 09:48
  • 1
    The quick answer is: no, this is not possible; not even with nested `call set` commands... – aschipfl Nov 14 '18 at 09:56
  • @GerhardBarnard Thank you, I saw it. I tried to do something "more pretty" (IMO) then using many comands in one line. – franiis Nov 14 '18 at 10:02
  • @aschipfl Thank you, I suspected it (I couldn't find a solution), but it's nice to be sure. I tried earlier `CALL` but also no luck. – franiis Nov 14 '18 at 10:04
  • IMHO this is what you are looking for: `for /F "delims=.," %%a in ("%time::=_%") do set "VAR=%%a"` – Aacini Nov 14 '18 at 14:27

1 Answers1

3

Although it is possible to do it in one line (delayed expansion needed), I don't think, it serves readability:

@echo off
setlocal enabledelayedexpansion
set "var=%time:~0,8%" & set "var=!var::=_!"
echo %var%

I suggest moving the formatting to a subroutine. (Not exactly a one-liner, but keeps your main code clean and readable).

@echo off
call :FormatTime var="%time%"
echo %var%
goto :eof

:FormatTime
  set "_=%~2"
  set "_=%_:~0,8%"  :: get 'HH:MM:SS'
  set "_=%_: =0%"   :: replace ' ' with '0' 
  set "%1=%_::=_%"  :: replace ':' with '_' 
goto :eof

The call defines the variable name for the result (var here) and the string to format (%time% here). Usually, the two arguments are separated by a space, but as = also acts as a standard delimiter, we can use that to make the line even more readable (intuitive).
Enclosing the string in quotes ("%time%) enables us to catch the space (" 8:12:00,99") to be able to replace it with a zero.

I also used another method to strip the milliseconds part (language independent).

Stephan
  • 53,940
  • 10
  • 58
  • 91
  • So do you think that a variable called `_` (underscore) is _readable_? **`:/`** – Aacini Nov 14 '18 at 14:30
  • 1
    @Aacini I'm sure, I said `keeps your *main code* ... readable`... I often use `_` as a temporary variable in subroutines, being sure, I don't overwrite any vital variables anywhere else. – Stephan Nov 14 '18 at 15:27