Reputation: 21
I have a file which have multiple row each row contains 3400 characters. I want to grep something from specified character range, let's say I want to grep "pavan"
between character range 14 to 25 in the line.
To do this I can simply do like below
cat filename | cut -c 14-25 | grep pavan
I tried to use awk command but it does not work since the lines have more than `3000 characters but by this complete line will not print.
I want to print complete line also so that I can perform further operation on it.
Upvotes: 2
Views: 692
Reputation: 246774
awk -v pattern="pavan" 'match( substr($0, 14, 11), pattern )' file
Will print the matching lines.
A more complicated way of doing the same thing:
awk -v patt="pavan" -v start=14 -v end=25 '
match($0,patt) && start <= RSTART && RSTART <= end-RLENGTH
' file
-- stricken due to valid commentary from Ed Morton.
Upvotes: 1
Reputation: 207425
This is not very elegant, but does work!
Start off with what you had, but remove the unnecessary cat
:
cut -c 14-25 file
now get awk
to find the string you want and print the line number:
cut -c 14-25 file | awk '/paven/{print NR}'
Now you have a list of all the line numbers that you want. You can either process them in a while loop, like this:
cut -c 14-25 file | awk '/pavan/{print NR}' | while read line; do
echo $line
sed -n "${line} p"
done
or put them in an array
lines=($(cut -c 14-25 file | awk '/pavan/{print NR}'))
echo ${lines[@]}
Upvotes: 0
Reputation: 123458
Some bit of arithmetic and you could use grep
:
grep -E '^.{13}.{0,7}pavan' filename
This would match lines containing pavan
between the specified character range.
It essentially matches 13 arbitrary characters at the beginning of a line. Then looks for pavan
that can be preceded by 0 to 7 arbitrary characters.
Upvotes: 0