My file file.txt
looks like this:
[NamesA]
Andreas
Alex
[NamesB]
Bernd
Bruno
[NamesC]
Casper
[NamesD]
Doris
I would like accomplish the following 3 different outputs, using grep
or awk
to use it in a bash script:
Output
[NamesB] Bernd Bruno
Output
[NamesB] Bernd Bruno [NamesC] Casper
Output
[NamesD] Doris
I tried:
grep -oP '\[NamesB\].*?' file.txt
but get only [NamesB]
and not the following textblock. I managed to get text which is direct behind, but not in a new line.
And that's it. If I would get at least all following lines starting with [NamesB]
, but even this did not work.
- So I can imagine the output for 1. might be the simplest by printing all starting with
[NamesB]
and ending at the next[
. - I also can imagine how this might work for 2.
Similar to output 1. but then running
grep
2 times. One time with[NamesB]
and then with[NamesC]
But how would this then work for 3. as there is no [
next. And it could be possible there is an unknown next block starting with [
.
The command should then start printing text starting with [NamesB]
or whatever and then stop either with the next opening bracket [
or by the end of the file.
PS: I posted a smilar question already and found a solution, but it was all one line of text. In this question i have a different situation of a text block and not a single line.
NamesB
is output twice, and the2. Output
contains twoNames
groups. Anyways, nope, that's not something that line-basedgrep
can do for you. You need to learn a scripting language and use that. Maybe you even already know one? Python? Go? awk? Perl? JavaScript?file.txt
? If not, please remove it. Do you really want the strings1. Output
,2. Output
etc in your output? And why is output repeated? Please show us the exact input and output.