Wednesday, May 25, 2022

[SOLVED] Print name of file if second line is empty

Issue

the file looks like this:

>5BW0 B
CHHHHHHHHHHHHHHHHHHHHHHHCCCCCCEEEEEEEEEECCEEEEEEEEEEECCCCCCEEEEEEEEECCCCCCCHHHHCCEEEEEEEC

However the second line could be empty.

I'm trying to find the files with empty second lines.

So far I came up with this in a for loop:

cat file1 | sed -n '2p' | grep '^$'

the problem is that I'm not saving the filename so that I can print it afterwards. How can I fix this?


Solution

With single GNU awk you could try following awk program. Written and tested in GNU awk. I have passed 2 Input_files named file1 and file2 in this program you can pass number of files as per your requirement also.

awk 'FNR==3{nextfile} FNR==2 && !NF{print FILENAME;nextfile}' file1 file2

OR as per Ed sir's recommendation above could be shorten to:

awk 'FNR==2{ if (!NF) print FILENAME; nextfile }' file1 file2

Explanation: Simply checking if its 3rd line of a file then move to next file anyways(which means 2nd line is NOT empty). Then checking 2 more conditions if line is 2nd line and is empty then print file name and move to nextfile.

NOTE: In case you need to find files which are having 2nd line as an empty and print their names then make this above code as a script.awk code and pass it to run in find command too.



Answered By - RavinderSingh13
Answer Checked By - Mildred Charles (WPSolving Admin)