Home > Mobile >  Piping date into string join command in fish
Piping date into string join command in fish

Time:06-09

I want to format the date command to use as a logging file name. Ideally I would like to use a command like this:

set dt (echo (date)) && string join '' $dt

When I run this I get the normal date output:

Tue Jun  7 22:25:26 PDT 2022

I want output like this:

TueJun722:26:09PDT2022

Is there a way to use a pipe command for this?

CodePudding user response:

The important part here is this:

Unlike bash, fish only splits command substitutions on newlines, not other whitespace. Spaces and tabs don't matter.

set dt (echo (date)) && string join '' $dt

What this does is:

  • Run date - this prints Tue Jun 7 22:25:26 PDT 2022
  • Split that on newlines. There's no newline (except at the end), so this ends up as one argument
  • Run the equivalent of echo 'Tue Jun 7 22:25:26 PDT 2022' and split it on newlines (once again no newlines in the string)
  • Run the equivalent of set dt 'Tue Jun 7 22:25:26 PDT 2022'
  • This succeeded (because echo did, and it basically always does), so we go on
  • Run the equivalent of string join '' 'Tue Jun 7 22:25:26 PDT 2022' - the variable was set to one argument, so it will expand to one argument (no word-splitting like in bash)
  • string join only adds the joiner between arguments, so since there is only one argument it is printed as-is

What you want is to either

  1. Remove all whitespace with string replace
  2. Split your date on whitespace, and then join it

The former:

set dt (date | string replace -ra '\s*' '')

This runs string replace in regex mode (-r) and tells it to replace all occurences in a line (-a - this is like seds '/g' modifier). string can take its arguments either on the commandline or via a pipe, if you have an external command anyway it reads better to pipe it, and you don't have to fiddle with the -- option separator.

The latter:

set dt (date | string split -n ' ' | string join '')

The -n means string split will skip empty entries. Note that the former removes all whitespace (including e.g. tab), while the latter only cares about actual space characters. For date it doesn't appear to make a difference.

Alternatively you can fiddle with date's format string. I'll leave that up to the reader.

  • Related