This (somewhat complicated) solution,
which is somewhat similar to Gilles’s answer,
- outputs no space at the beginning of the line,
- correctly handles the case where the input line begins with whitespace, and
- preserves inter-field whitespace.
awk -v word=alpha '
$2 == word {
i = index($0, $1) # Find $1 within $0 (the line).
if (i > 0) { # Sanity check; should always be true.
i = i + length($1) # Find space after $1.
temp = substr($0, i)
i = index(temp, $2) # Find $2 in remainder of line.
if (i > 0) { # Sanity check; should always be true.
print substr(temp, i)
}
}
}'
I believe the in-line comments explain it fairly well.
We find $1’s position in the line
(remember, I’m explicitly not assuming that it’s at the beginning).
Then, à la Gilles’s answer,
we strip $1 (and the whitespace before it, if any) off the line.
Then find $2’s position in the remainder of the line,
and strip off the whitespace before that.
Here is a slight streamlining of Dennis Williamson’s answer.
awk -v word=alpha '$2==word { for (f=2; f<=NF; ++f) printf("%s%s", $f, (f==NF?ORS:OFS)) }'
Like Dennis’s answer,
it outputs the fields $2, $3, …, $NF (omitting $1)
with default separation.
Dennis took the approaching of preceding $3, …, $NF (but not $2)
with the default output field separator.
I took the approach of following $2, $3, …, $(NF-1) (but not $NF)
with the OFS.
And, since $NF is followed by the output record separator (ORS),
we can use a ?: operator with no null terms,
and eliminate the final printf("\n").
$NF/NF/). You can useif (f!=2) {printf("%s",OFS);} printf("%s",$f);as the loop body. – Gilles 'SO- stop being evil' Nov 21 '10 at 16:10dto""; as written, it will only work as intended for the first line. – dubiousjim Apr 19 '12 at 11:07alpha beta gama), this will replace them with single spaces (alpha beta gama). Not that the OP expresses a requirement to preserve the inter-field whitespace. – Scott - Слава Україні Jan 16 '17 at 04:43