0

I want to search a file to output rows matching a particular value at specific column number. There is no delimiter involved. For example:

IloveA
IloveB
IloveC
IloveA
IloveD
IloveA
Ilove A

Output :

IloveA
IloveA
IloveA

Here the important point to note it should print only if A is present at 6th column.

oguz ismail
  • 1
  • 16
  • 47
  • 69

2 Answers2

0

Use grep '^.....A' or more generally grep -E '^.{5}A'.

August Karlstrom
  • 10,773
  • 7
  • 38
  • 60
0

As I understand the problem, you need to print the rows matching a pattern within the range of the first 5 characters, but only if the 6th character is A. This can be done in two steps:

  • filter out the rows with the 6th character equal to A and capture the first 5 characters at the same time;
  • print the line, if the captured sequence matches your pattern.

The following is a sample implementation of the above in Perl:

perl -l -n -e 'print if /^(.{5})A/ and $1 =~ /ove/' input-file.txt

The Perl code prints the next line read from the file (implicit argument $_) if the line matches /^(.{5})A/. As a result of capturing, $1 (the first and the only capturing group) contains the first five characters. Then, if $1 matches /ove/ (a sample pattern that you'd change), the second if condition is true, and the line is printed to standard output.

Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60