Home > Net >  find text in file starting from nth line onwards, using shell script
find text in file starting from nth line onwards, using shell script

Time:03-16

I am trying to search for a keyword in a file, starting from the nth line onwards. And if its found, set a variable to true For example, file contents of testtext.txt:

abc-0
def-0
xyz-0
abc-1
xxx-1

I want to search keyword 'def' from the 3rd line onwards and if found, print true. Also assuming the nth line is a pass in value.

I have a rough idea below, but not sure how to fix it.

#!/bin/bash

keyword=def
nthline=3
flag=false

count=$(awk 'NR>$nthline' ./testtext.txt | grep '$keyword' | wc -l)
if [[ $count -gt 0 ]];then
  flag=true
fi

echo $flag

Expected output should be false, because def doesnt exist on the 3rd line onwards.

Problem is I cannot pass in the 'nthline' variable into the NR> of awk and also cannot pass in $keyword to the grep on that line

I have tested using actual values instead of pass in, it works, so the commands should be working.

count=$(awk 'NR>3' ./testtext.txt | grep 'def' | wc -l)

Is there any way to do this, or any other better solution?

CodePudding user response:

It would be best to do this entirely in awk since you are already using awk to slice the file.

Example:

tgt="def"
n=3

awk -v tgt="$tgt" -v n="$n" '
BEGIN{flag="false"}
FNR>=n && index($0,tgt){
    flag="true"
    exit
}
END{print flag}' file

Alternatively, you can make a pipe and then inspect $? to see if grep found your match:

tgt="def"
n=2

tail -n " $n" file | grep "$tgt" >/dev/null

Now $? will be 0 if the grep finds the pattern and 1 if it is not found. Then you can set a flag like so:

flag="false"
tail -n " $n" file | grep "$tgt" >/dev/null 
[ $? ] && flag="true"

Now flag is set true / false based on the grep. The command tail -n [some number] file will print the file contents from the absolute line number onward.

For large files, the awk is significantly more efficient since it exits on the first match.

CodePudding user response:

Suggesting:

awk 'NR > 3 && /def/{print 1}' RS="$^" testtext.txt

CodePudding user response:

Try:

tail -n " $nthline" testtext.txt | grep -qF -- "$keyword" && flag=true || flag=false
  • Related