0

How in Bash to generate a string given by a regex expression and pipe it to another command?

For example:

> $RANDOM | regex "{abcdef\d}[8]" | grep "1{3}" | less

I did not find which utility can generate strings based on a regex expression special

The regex expression is the input. I want to find a utility that generates strings based on regex.

For example:

> regex "{abcdef\d}[8]" -n 10

b8789a62 97303666 8b536c28 79590607 6d80ad60 78d36ded aa001d9a 8826f276 df1e1f7a 854307db

Aycon
  • 1
  • 1
  • I don't know of any existing tools which can do this, but [there are plenty of libraries](https://stackoverflow.com/a/43377488/2072269) which can do this, so you could use one that works with Python or Perl to do the job – muru Jan 13 '23 at 14:35
  • Thanks, but isn't there something built into bash? Possibly ineffective, with brute force. I can't install libraries. – Aycon Jan 13 '23 at 14:41
  • See this previous question [How to generate a random string?](https://unix.stackexchange.com/questions/230673/how-to-generate-a-random-string) – steeldriver Jan 13 '23 at 14:41
  • Regular expressions are strictly used in the opposite direction: you already have a string and you need to check that it matches the pattern. Regular expressions are not applicable for _generating_ strings. – glenn jackman Jan 13 '23 at 14:57

1 Answers1

1

To get a stream of lines, each with eight lower-case hexadecimal digits, you may use

tr -c -d '0-9a-f' </dev/random | fold -w 8

This reads from /dev/random and removes all characters we're not interested in using tr. fold is then used to cut the stream up into lines of eight characters.

Modify the tr selection expression to select any other set of characters. Modify the fold length to get longer or shorter strings. Add a grep stage to the pipeline if you want to pick out strings that fulfil other criteria from the generated ones, for example, use grep 111 to only allow strings that contain three consecutive 1.

Kusalananda
  • 320,670
  • 36
  • 633
  • 936
  • How about any regular expression? – Aycon Jan 13 '23 at 14:39
  • 1
    @Aycon, regex have different role, to map input string , not to generate something. – Romeo Ninov Jan 13 '23 at 14:44
  • @Aycon "Any regular expression" does not make sense. You will need to explain a bit further what it is you want to do. It is highly unusual that the regular expression is a parameter in a problem. Is the question really about generating all possible strings that match a given expression, because that seems to be what you are asking? – Kusalananda Jan 13 '23 at 14:47
  • like this, but in bash terminal: https://www.browserling.com/tools/text-from-regex – Aycon Jan 13 '23 at 14:51
  • @Aycon, add on the end of the line (after `fold` command) `|grep "{abcdef\d}[8]"` and this will filter only strings which map this regex – Romeo Ninov Jan 13 '23 at 14:55
  • 1
    Thank you. Ok, I'll just develop this utility) – Aycon Jan 13 '23 at 15:03