Reputation: 3236
I have spent some time considering how to tackle this but i'm not sure and my use of unix is fairly limited so far.
I have a text file, lets give it a name "Text.txt", which contains lots of information. Let's say it contains:
SomethingA: aValue
SomethingB: bValue
SomethingC: cValue
SomethingD: dValue
SomethingD: anotherDValueThisTime
SomethingA: aValueToIgnore
I want to search through "Text.txt", and find some values, then put the values in a new file, output.txt.
This gets a little bit more tricky tough, as what I am trying to do is get the first value of somethingA, and then every SomethingD value which occurs.
So the output in "output.txt" should be:
aValue
dValue
anotherDValue
The second "SomethingA" value wants to be ignored as this is not the first "SomethingA" value.
I imagine the logic to be something like: Find SomethingA > output.txt Find ALL SomethingD's >> output.txt
But I just can't quite get it. Any help is much appreciated!
Upvotes: 1
Views: 9653
Reputation: 1
I think what you need is the grep
command with the -o
options. It works like this:
grep -o -e 'pattern1' -e 'pattern2' /tmp/1 >> /tmp/2
Upvotes: 0
Reputation: 45122
grep -m 1 somethingA inputfile.txt >outputfile.txt
grep somethingD inputfile.txt >>outputfile.txt
grep
option -m
sets the maximum number of matches you want to get.
>>
appends to a file rather than overwriting it like >
does.
Upvotes: 1
Reputation: 212248
awk
is ideal
awk '/^SomethingA/ && ! a++ || /^SomethingD/ { print $2 }' FS=: text.txt > output.txt
This is a little sloppy, but you can be more precise with:
awk '$1 == "SomethingA" && ! a++ || $1 == "SomethingD" { print $2 }' FS=: text.txt > output.txt
Unfortunately, that requires a fixed string for the keys. If you want a regex, you can do:
awk 'match($1, "pattern") && ...
Upvotes: 2