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

Advertisements

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.

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

Leave a Reply Cancel reply