-1

I need to find all the positions of a specific character ## in a file using Bash script and also store all positions for future use.

This is how the file looks like:

assert property ( ( req1 == 0 ) ##1 ( req1 == 1 ) ##1 !( req2 == 1 ) || (gnt1 == 0 ) );
assert property ( ( req1 == 0 ) ##1 !( req1 == 1 ) || ( gnt1 == 1 ) );
assert property ( ( req1 == 1 && req2 == 0 ) ##1 !( req2 == 1 ) || ( gnt1 == 0 ) );

In the above file I want to get all locations for this character (##) and store them as well. How can this be done using shell script?

Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60
mii9
  • 27
  • 5

2 Answers2

1

You could use awk for this:

awk -F'##' '
{
   for(i=1;i<NF;i++){
     printf "%d ",length($i)+offset+1
     offset+=length($i)+length(FS)
   }
   printf "\n"
   offset=0
}' file

The parameter delimiter -F is set as your pattern.

Loop through all portions of the line ($1,$2...) and print the length of each portion that actually indicates the position of the pattern (adding the offset for line that would contain more than one match).

oliv
  • 12,690
  • 25
  • 45
0

Try this

#!/bin/bash

str1="assert property ( ( req1 == 0 ) ##1 ( req1 == 1 ) ##1 !( req2 == 1 ) || (gnt1 == 0 ) );"
str2="assert property ( ( req1 == 0 ) ##1 !( req1 == 1 ) || ( gnt1 == 1 ) );"
str3="assert property ( ( req1 == 1 && req2 == 0 ) ##1 !( req2 == 1 ) || ( gnt1 == 0 ) );"

char="##"

awk -v a="$str1" -v b="$char" 'BEGIN{print index(a,b)}' | xargs expr -1 +
awk -v a="$str2" -v b="$char" 'BEGIN{print index(a,b)}' | xargs expr -1 +
awk -v a="$str3" -v b="$char" 'BEGIN{print index(a,b)}' | xargs expr -1 +

The positions are 32, 32 and 45 for these examples. But there is only the first appearance of the ## char for each one. Not sure if you need to get more appearances.

Solution extracted from Dennis Williamsons comment on this post

Community
  • 1
  • 1
OscarAkaElvis
  • 5,384
  • 4
  • 27
  • 51
  • Thank you, but I need to know the positions of all occurrences in the file for this character. – mii9 Dec 07 '16 at 14:14