Text Processing – How to Print File Content Only if the First Line Matches a Pattern

filesregular expressiontext processing

I am writing a script, I want to check if the first line of the file matches a certain pattern and if it does then print out the file. How can I achieve this?

How do I check for pattern? Is there a way to check for pattern and based on the output do something..

EDIT:
Please take a look at this question: https://stackoverflow.com/questions/5536018/how-to-get-match-regex-pattern-using-awk-from-file

I want something like this, but none of them worked for me. I basically want to check if the first line matches a regex pattern or not and based on that print the lines of file.

Best Answer

You could do that with ed:

ed -s infile <<\IN 2>/dev/null
1s/PATTERN/&/
,p
q
IN

the trick here is to try to replace PATTERN on 1st line with itself. ed will error out if it can't find the specified pattern so ,p (print whole file) will only be executed if 1s/PATTERN/&/ is successful.

Or with sed:

sed -n '1{
/PATTERN/!q
}
p' infile

this quits if the first line does not (!) match PATTERN, otherwise it prints all lines.
Or, as pointed out by Toby Speight, with GNU sed:

sed '1{/PATTERN/!Q}' infile

Q is the same as q but it does not print the pattern space.

Related Question