To catch the beginning of a sequence from a file

I have a text file that looks like this:

125 126 127 { 566 567 568 569 # blah blah 570 { #blah blah 700 701 { 

The numbers are left justified, and the pattern is always the same in terms of enlargement and braces at the end. I need to catch only the starting number. Brackets are always found and bounded by the end of the sequence. The beginning of the file, as shown, starting with '125'.

In short, I need:

  125 566 700 

What I came up with:

  grep -A1 '{' | grep -v '{' | grep -oE '(^[0-9]+?)' 

but it omits 125 ', but I overcame by adding a new line to my head and inserting { .

I hope to bring this into one regular expression.

Suggestions and best algorithms are welcome.

+6
source share
6 answers
 awk 'BEGIN {p=1} p==1 {print $1;p=0} $0~/{/ {p=1}' Output: 125 566 700 

Given the file format above, you can use awk and a variable / flag to keep track of when you discover the opening {

+4
source
 sed -n '1p;/{/{ N s/.*\n\([0-9]\+\).*/\1/p }' input_file 
+3
source

You may need to configure a regex, but:

 awk '!k; { k = !/^ *[0-9]* *{/ }' 

This will print the first line and any line following the line that matches the regex ^ *[0-9]* *{ You could probably simplify things and do:

 awk '!k;{k=$2!="{"}' 

Which will print the first line and any line following the line in which the second field is the only open curly brace.

+2
source

I would use awk and a flag to capture the existence of a curly brace and print the next line. Set the flag at the beginning and you will get the first line.

Unconfirmed, but something like:

 BEGIN {hasCurly = 1} { if(hasCurly) print $1; hasCurly = match($2,"^\{"); } 
+1
source

Here is a clean bash solution:

 start=1 while read n rest; do if (( start )); then printf '%d\n' $n start=0 elif [[ $rest = \{* ]]; then start=1 fi done < input 
+1
source

sed will win the golf code competition =):

 sed -n '1p;/{/{n;p}' file 

To delete everything after using the number:

 sed -n '1{s/\s*\([0-9]\+\).*/\1/;p};/{/{n;s/\s*\([0-9]\+\).*/\1/;p}' file 
+1
source

Source: https://habr.com/ru/post/920120/


All Articles