regex character appears exactly x times <p>I'm working in bash and I have a large file in which I want to remove all the lines that do not match a certain regex, probably using <code>$ grep -e "&lt;regex&gt;" &lt;file&gt; &gt; output.txt</code> </p> <p>What I want to keep is any line that contain exactly <em>x</em> times a specified character, for example in the binary sequence </p> <blockquote> <p>0000, 0001, 0010, 0011, 0100, 0101, 0111, 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111</p> </blockquote> <p>I would like to keep only those who have 2 <em>1</em>, leaving me with</p> <blockquote> <p>0011, 0101, 0110, 1001, 1010, 1100</p> </blockquote> <p>I would then use a bash variable to vary the amount I need (always exactly half of the length, working with strings of the same length) I'm litterally looking for lines that are half <em>0</em> and half <em>1</em></p> <p>I have this right now. It's not using regex. It works, but is very slow:</p> <p>(<code>$1</code> is the length of every string, <code>$d</code> is just a directory)</p> <pre><code>sed -e 's/\(.\)/\1 /g' &lt; $d/input.txt &gt; $d/spaces.txt awk '{c=0;for(i=1;i&lt;=NF;++i){c+=$i};print c}' $d/spaces.txt &gt; $d/sums.txt grep -n "$(($1/2))" $d/sums.txt | cut -f1 -d: &gt; $d/linenums.txt for i in $(cat $d/linenums.txt) do sed "${i}q;d" $d/input.txt done &gt; $d/valids.txt </code></pre> <p>In case you wonder this puts spaces in between every digit turning <code>1010</code> into <code>1 0 1 0</code>, then it adds the values together, saves the results in sums.txt, grep for length/2 and save only the line numbers in linenums.txt, then it reads linenums.txt and outputs the corresponding line from input.txt to output.txt</p> <p>I need something quicker, the for loop is what's taking way too long</p> <p>Thanks for your time and for sharing your knowledge with me.</p>