0

i have a problem with a task from title. By using SED i have to display lines with 3 'x' signs.

I know how to do it with one sign, but i can't write working command for 3 signs.

Example input:

   blaxblax 
   xxox
   xxx23
   0x1a
   xxxx

output:

   xxox
   xxx23
4

What you need to do here is create a regular expression that matches:

  • starting from the beginning of the line, (zero or more non-"x" characters followed by an "x") 3 times
  • followed by zero or more non-"x" characters until the end of the line

With sed you'd write (assuming GNU sed)

sed -rn '/^([^x]*x){3}[^x]*$/p'
|improve this answer|||||
4

Short GNU awk approach:

awk -v FPAT='x' 'NF==3' file
  • FPAT - pattern defining field value
  • NF - total number of fields (in our case - the number of x char occurrences)

The output:

xxox
xxx23
|improve this answer|||||
1
sed -n '/x\{2,3\}/p' test.txt |sed '/x\{4,\}/d'

Output:

xxox
xxx23
|improve this answer|||||
0

Another GNU sed approach

sed -n 's/x/x/3;T;s/x/x/4;t;p'

POSIXly, you'd use grep, no need for sed for that:

grep -Ex '([^x]*x){3}[^x]*'

grep pattern can always be written sed '/pattern/!d' though POSIX sed only understands BREs so:

sed '/^\([^x]*x\)\{3\}[^x]*$/!d'

With awk:

awk -F x 'NF == 4'
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.