Blog Linux Unix

how to get the first file in unix

In case you are looking files using ls or find command and only want to get the first file found, the command would be like.

ls -l /any/path/filename*|sed -e 's///,/g'|awk -F "," '{print $NF}'|head -1

Of course, you can also use it in find command.

find /any/path/ -name "filename*" -type f|sed -e 's///,/g'|awk -F "," '{print $NF}'|head -1

The key here is the head -1 command which limits the output to just one line. I came about this when I was investigating a problem in one of the programs that I maintain. The original code is as below.

inputFile=`ls -l /any/path/filename*|sed -e 's///,/g'|awk -F "," '{print $NF}'`

It looks correct, runs perfectly during testing and there seems to be no problem. However, if there's more than one file, the variable inputFile will have multiple-line data. When used in a command, the problem starts. Basically, it was only expecting one file. When more than one file is push, inputFile should just get the first file. That's why pipe-in another command which is the head -1.

In case you need the last file, then just change the head -1 to tail -1.

Bugs like this is hard to find. When we test or investigate, we usually use just one file to run through the whole program. And that's what happened with this issue was raised to me. The previous developer is already pulling his hair because in order to get to that problematic line, he had to go trace it though a deep layer of shell scripts.