3

I'm trying to fix a bash script by adding in some error catching. I have a file (list.txt) that normally has content like this:

People found by location:  
person: john [texas]  
more info on john

Sometimes that file gets corrupted, and it only has that first line:

People found by location:

I'm trying to find a method to check that file to see if any data exists on line 2, and I want to include it in my bash script. Is this possible?

4

4 回答 4

2

Simple and clean:

if test $(sed -n 2p < /path/to/file); then
    # line 2 exists and it is not blank
else
    # otherwise...
fi

With sed we extract the second line only. The test expression will evaluate to true only if there is a second non-blank line in the file.

于 2013-08-28T16:05:57.023 回答
1

I assume that you want to check whether line 2 of a given file contains any data or not.

[ "$(sed -n '2p' inputfile)" != "" ] && echo "Something present on line 2" || echo "Line 2 blank"

This would work even if the inputfile has just one line.

If you simply want to check whether the inputfile has one line or more, you can say:

[ "$(sed -n '$=' z)" == "1" ] && echo "Only one line" || echo "More than one line"
于 2013-08-28T16:09:52.353 回答
1

Sounds like you want to check if your file has more than 1 line

if (( $(wc -l < filename) > 1 )); then
    echo I have a 2nd line
fi
于 2013-08-28T16:53:58.760 回答
0

Another approach which doesn't require external commands is:

if ( IFS=; read && read -r && [[ -n $REPLY ]]; ) < /path/to/file; then
    echo true
else
    echo false
fi
于 2013-08-28T16:38:32.693 回答