Issue
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}'
Further examples and what would be expected as a result.
$ echo "-ntest-name -ntest" | ...
test-name
$ echo " -n test-name -n test-n" | ...
test-name
$ echo "-na test-name -n test-n" | ...
test-n
$ echo "- n-name -nn test" | ...
n
$ echo "-a -e -i -o" | ...
$ echo "-an -en --n foo" | ...
$ echo "-nbar" | ...
bar
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"
orecho "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
Answered By - markp-fuso Answer Checked By - Terry (WPSolving Volunteer)