Reputation: 153
Please, accept my apologies, if this question was asked before. I am new and do not know how to do it. I have a file containing the data like this:
name=1|surname=2|phone=3|email=4
phone=5|surname=6|name=7|email=8
surname=9|phone=10|email=11|name=12
phone=13|email=14|name=15|surname=6
I would like to have a file like this:
name=1
name=7
name=12
name=15
Thanks in advance!
Upvotes: 1
Views: 5819
Reputation: 19982
I would go for the solution of @Lars, but I wanted to test this with "lookbehind".
With grep
you can get the matches only with grep -o
, but the following line will also find surname:
grep -o "name=[0-9]*" names.txt
You can fix this a little by looking for the character before name (start of line with ^
or |
).
grep -o "(^|\|)name=[0-9]*" names.txt
What a fix! Now you get the right names, but sometimes with an extra |
.
With \K (and grep option -P) you can tell grep to use something for the matching but skip it during output.
grep -oP "(^|\|)\Kname=[0-9]*" names.txt
Upvotes: 0
Reputation: 10139
Say names.txt is your file, then use something like :
cat names.txt | tr "|" "\n" | grep "^name="
tr
transforms |
to newlines grep
filters for the lines with nameAnd here is a one command solution with GNU awk:
awk -v RS="[|\n]" '/^name=/' names.txt
-v RS="[|\n]' set the record separatro to
|` or newline/^name=/
filters for records starting with name=
(and implicitly prints them)Upvotes: 2