I'm looking to write a shell script that grabs a line number from a file using grep, and use that line numbers as head and tail for sed command to cut the file.
My script looks something like this:
head=$(grep -n -i -B 1 "^\s\+abcd" <sourcefilename> | head -n 1 | cut -d: -f1)
tail=$(grep -n -i -B 1 " efgh" <sourcefilename> | tail -n 1| cut -d: -f1)
if($head!=NULL)
then
sed -n "$head,$tailp" <sourcefile>.txt > <newfile>.txt
fi
My goal, is to use first grep, and get the head line number when it matches the pattern, then use the second grep to get tail line number when it matches the pattern, and use those to as inputs for sed with -n switch and create a file that only has line numbers from head to tail.
If I execute it individually against the file, like
grep -n -i "^\s\+abcd" <filename> | head -n 1 | cut -d: -f1 , it gives me 11 and
grep -n -i " efgh" <filename> | tail -n 1| cut -d: -f1 gives me 106.
Then I used these numbers as inputs and do
sed -n 11,106 <sourcefile>.txt > <newfile>.txt
it works perfectly. I'm trying to automate the process to have a script that can run against multiple files at once.
Also, the if statement with NULL means when grep doesn't return anything, just don't run the loop, which seems to also error out.
$tailpis trying to expand a variable namedtailp. If you want the value in the variabletailfollowed by ap, use${tail}p- William Pursell