Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pattern extraction matching pattern a OR pattern b (sed/awk)

How do I extract the word after the first -n whether or not there is a blank space after?

In the example below it would return test-name on both cases. This awk code is working properly only on the first example.

$ echo "a -n test-name -bc d-e -fe -ntest" | awk 'BEGIN{FS="-n  *"}{sub(/ .*/,"",$2);print $2}'                                                                              SIGINT 
test-name

$ echo "a -bc d-e -fe -ntest-name -ntest" | awk 'BEGIN{FS="-n  *"}{sub(/ .*/,"",$2);print $2}'

-n could be considered as a classic bash flag, which accepts an argument either -ntest-name or -n test-name. In this case test-name would be the argument.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

sed would also be a option.

Could this be done with a one-liner? Thank you.

>Solution :

One awk approach:

$ echo "a -n test-name -bc d-e -fe -ntest" | awk '{line=substr($0,$0~/^-n/ ? 3 : index($0," -n")+3); split(line,a); print a[1]}' 
test-name

$ echo "a -bc d-e -fe -ntest-name -ntest"  | awk '{line=substr($0,$0~/^-n/ ? 3 : index($0," -n")+3); split(line,a); print a[1]}'
test-name

$ echo "-ntest-name a -bc d-e -fe -ntest"  | awk '{line=substr($0,$0~/^-n/ ? 3 : index($0," -n")+3); split(line,a); print a[1]}'
test-name

NOTES:

  • could be further modified if there’s an additional delimiter after the value that we need to filter for, eg, echo "-ntest-name|new_command" or echo "a b -n test-name; next_command"; would need to know the potential set of additional delimiters
  • assumes the input has a valid -n to process otherwise this will print everything from the 3rd input character up to the 1st space (eg, echo "test-name" => st-name; this could be addressed with additional code
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading