1

I need a command in Unix to look for a pattern in specific columns in a fixed length file and output the entire line to a different file.

Example File1

2345abcdef450022677
1234sdfght350022677
3456abcdef350022677

I need extract the lines if column 5 to 10 = abcdef and column 15 to 16 = 22.

I want the output file to have the following data.

2345abcdef450022677
3456abcdef350022677

I can use the cut command with grep to find the pattern but not sure how to output the entire line.

5

Try this

$ cat foo
2345abcdef450022677
1234sdfght350022677
3456abcdef350022677
$ grep -E '^.{4}abcdef.{4}22' foo >foo2
$ cat foo2
2345abcdef450022677
3456abcdef350022677
$

or

$ awk 'substr($0,5,6)=="abcdef" && substr($0,15,2)=="22"' foo >foo2
$ cat foo2
2345abcdef450022677
3456abcdef350022677
$

or even

$ grep '^....abcdef....22' foo >foo2
$ cat foo2
2345abcdef450022677
3456abcdef350022677
$

and finally, using sed (checks that 5th to 10th is abcdef and 15th to 16th is 22 and if not deletes the line, credit to user112638726 for this)

sed '/^.\{4\}abcdef.\{4\}22/p;d' foo
  • Add my command to your answer if you want, pretty much the same thing and probably better to have one comprehensive answer. I'll delete mine if you do :) – 123 Jun 24 '15 at 20:13
  • Thanks. For some reason the grep -E did not work for me... ( Worked fine with example but not with the actual file). The awk command worked great. Thank you so much. – manchand Jun 24 '15 at 20:20
1

In sed

sed '/^.\{4\}abcdef.\{4\}22/p;d' file

Checks that 5th to 10th is abcdef and 15th to 16th is 22 and if not deletes the line

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.