Find position of a character in a file and store its position bash

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?


ANSWERS:


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).


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



 MORE:


 ? Bash checking if string does not contain other string
 ? Bash checking if string does not contain other string
 ? Bash checking if string does not contain other string
 ? Bash checking if string does not contain other string
 ? Comparison of 2 string variables in shell script
 ? Comparison of 2 string variables in shell script
 ? Comparison of 2 string variables in shell script
 ? Comparison of 2 string variables in shell script
 ? difference between sh and bash when symlink is used
 ? Get files in bash script that contain an underscore