I want to extract out those lines that contain
g__something not followed by
s__something in the lines. How can I do that?
This awk command will unconditionally print the first two lines of
file and print other lines that contain
g__ except where it is followed by
awk 'NR<3 || /g__/ && !/g__.*s__/' file
Note that this solution will print lines where
g__. If you want to exclude lines containing
s__ regardless of whether it comes before or after
g__, change the second condition to
This can be easily done in python3. The following program will print lines containing "g__" but not containing "s__".
Paste this in a file called
find_g.py and put the data in
import sys # Open the file for reading with open(sys.argv) as f: # Print first two lines without any condition print(f.readline(), end='') print(f.readline(), end='') # Check for condition in rest of the file for line in f: if "g__" in line and "s__" not in line: print(line, end='')
python3 find_g.py data.txt
Your requirements are: extract the first two lines and then the lines that contain the pattern "g__" but not "s__"
One simple way is the following:
head -2 inputfile > outputfile; grep "g__" inputfile | grep -v "s__" >> outputfile
The part before ';' extract the first two lines of inputfile and put them in outputfile. The part after ';' at first extract all lines containing "g__" and then, among them, remove the ones with the pattern "s__". These lines are then appended using >> operator in outputfile, so that the lines added before are not overwritten.
This is a very simple approach to the problem. For sure there are other solutions in terms of performances (maybe awk works better in case of huge files) and maybe more elegant than this one.