i have a file in directory which has some values like this
lets assume the file is $p
ttry_rtyy_trree
and i am using a file as an input as ($Y) in a shell once i start the shell it should read the file $p and $Y once those lines are matched in $Y i want to take a copy of that line and lines which are below 7 lines and put it in a output file ($Z)
$Y has this
ttry_rtyy_trree
66341251111
14567888888
12323434343
23232454544
2323234354
354545476767
67676767676676
9834587957457439
100192903203239
and my Output file after extracting should be exactly like this
You can do this using a "while read" loop and an if that matches for the line pattern you want, then printing the next seven lines by reading them repeatedly. You can also do this using awk, where after you get a match, run a loop where you print and getline repeatedly.
>$Z #truncate file in $Z to ensure that we start with an empty file
while read line; do
awk '/'$line'/ {for(i=0;i<7;i++) {print; getline}}' $Y >> $Z #actual work here
done < $p #read file in $p line-by-line and process each line in while loop
This will work if the pattern in $line occurs only once in the file. If the pattern repeats, you will get multiple outputs for each pattern that is repeated.
#!/usr/bin/env sh
# @(#) s1 Demonstrate match and copy with sed.
set -o nounset
echo
## Use local command version for the commands in this demonstration.
version bash sed
echo
cat >data1 <<'EOF'
a
1a
b
1b
c
1c
a
2a
b
2b
EOF
# Search for pattern "a" at beginning of line, then copy it and 1 more line.
sed -n -e '/^a/,+1p' data1
exit 0
Producing:
% ./s1
GNU bash, version 2.05b.0(1)-release (i386-pc-linux-gnu)
GNU sed version 4.1.2
a
1a
a
2a
Change to suit your situation, see man sed for details ... cheers, drl