2

I have a file of the following form (with '-' serving as delimiters), and I want to find the appearance of a number only when it follows a delimiter. I suppose it's a concatenation of grep '-\n' and $number, but I can't find the way to do it right. thanks..

1400 2 132 342 - 76567 1 1234 - 87 2 1400 54 - 
1
  • 1
    By modifying your question like that 3 months later, you're invalidating all the answers you've received. It's also unlikely that people will notice that you've changed the requirements. It would be better to ask a separate question. Commented Jun 17, 2014 at 22:01

5 Answers 5

5

To find variable before the delimiter:

Using awk:

$ awk '/!!!!!!!!!!!/{print num}{num=$0}' inputFile 342 1234 54 

or gnu-awk:

$ gawk 'NF && $0=$NF' RS='[!]+' inputFile 342 1234 54 

To find variable after the delimiter:

Using awk:

$ awk '/!!!!!!!!!!!/{if(getline) print $0}' inputFile 76567 87 

or gnu-awk:

$ gawk 'NR>1 && $0=$1' RS='[!]+' inputFile 76567 87 
5
  • we can shorten your version: awk '/!!!!!!!!!!!/{if(getline){print}}' file Commented Mar 16, 2014 at 13:20
  • 1
    Good that you have provided both the variants; given that the question doesn't make it clear! Commented Mar 16, 2014 at 13:23
  • Thanks @devnull. Yea, I was pretty much certain what I had in earlier was what OP wanted until a new answer came in which completely threw my understanding of the question. So went with both! :) Commented Mar 16, 2014 at 13:25
  • @jaypalsingh The level of tolerance for not-so-good-quality-posts is considerably higher on this site in comparison to SO. As such, rather vague questions keep getting attracted. Commented Mar 16, 2014 at 13:31
  • 1
    @jaypalsingh nice!!!!!! :D Commented Mar 16, 2014 at 13:33
1

The following command

grep '!!' -A 1 file|grep -vE '!!|\-\-' 

will yield

76567 87 
1
  • You read my mind... Commented Mar 16, 2014 at 13:12
1

grep has a switch -A that tells it to print a number of lines after the match. In this case, just use -A 1 and you'll get ouptut like

!!!!!!!!!!! 76567 -- !!!!!!!!!!! 87 -- !!!!!!!!!!! 

Now just grep out the numbers with | grep -e '[0-9]'.

1
  • grep --no-group-separator -A1 '!' inputFile | grep -v '!' would be better. Commented Mar 16, 2014 at 14:19
1

using AWK

To find variable before the delimiter:

awk '{ print $NF }' RS='!!!!!!!!!!!' infile 

Output

342 1234 54 

To find variable after the delimiter:

awk 'NR>1{ print $1 }' RS='!!!!!!!!!!!' infile 

Output

76567 87 
0

This does a number before a delimiter:

sed -n '/[^0-9]/!h;/^-$/{g;/./p}' 

And this after:

sed -n '/^-$/{n;/./!d;/[^0-9]/!p}' 

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.