0

I want to be able to extract a flag (-q) and its value from a string. An example:

<string1> -q <value> <string2>

Here, <string1> and <string2> can contain any set of characters. To clarify <string1> and <string2> are placeholders for any possible string.

I want two things:

  1. Be able to get the string <string1> <string2>
  2. Be able to get the string <value>

I would also be able to do something similar for this input:

<string1> --all <string2>

where --all is extracted and <string1> <string2> is is kept.

Unlike the proposed solution in How do I parse command line arguments in Bash?, I want to be able to extract a flag and its value and then keep the original command line input without the flag and that value.

toerq
  • 117
  • 2
  • 10
  • Are you actually trying to parse command-line arguments? – tripleee Feb 11 '19 at 09:26
  • Yes, I am. Normally all strings entered to my script are not using flags. So basically I am simply parsing e.g. $1, $2, etc. The reason for this is that my script is supposed to increase productivity for entering similar commands over and over and entering flags takes too much time. – toerq Feb 11 '19 at 09:29
  • For given input below one should work, your question should be more informative, for more answers. `$ echo ' --all ' | grep -Po "(?<=).*(?=\s*)"` – Akshay Hegde Feb 11 '19 at 09:34
  • @tripleee That duplicate does not answer how to extract the values from an existing string. – toerq Feb 11 '19 at 09:38
  • Just assign the string to `$@` with `set` or similar. – tripleee Feb 11 '19 at 09:45
  • @tripleee Yeah it worked, thanks – toerq Feb 11 '19 at 09:48

1 Answers1

0

A quick and very simple solution using cut:

 echo "<string1> -q value <string2>" | cut -d'>' -f2 | cut -d'<' -f1

outputs : -q value

NOTE this only works if whatever is between your string1 / string2 tags does not contain <>

nullPointer
  • 4,419
  • 1
  • 15
  • 27
  • >Here, and can contain any set of characters. So, for example "echo "asd qweqwe adssad -q value qwewqe asdasdasd qweqweewq asdasd" | cut -d'>' -f2 | cut -d'<' -f1" will not work – toerq Feb 11 '19 at 09:26
  • @toerq if the value you passed is between the string1 string 2 tags, it works. : `echo "asd qweqwe adssad -q value qwewqe asdasdasd qweqweewq asdasd" | cut -d'>' -f2 | cut -d'<' -f1` in your comments you missed the string1/2 tags in the echo – nullPointer Feb 11 '19 at 09:29