64.3k views
1 vote
That English paper you were writing on the works of Lewis Carroll is due in a few hours and you have forgeotten the name of the text file in which you had written a number of quotations to use in your paper. Luckily, you know that the file is somewhere in your ~/UnixCourse directory or in some subdirectory directly or indirectly within it. You also know that the file name ended in ‘.txt’. You are pretty sure that you could recognize the file from just the first line.

You seem to recall having heard that there is a Unix command head that will print the first few lines of any file and suspect that, with the proper parameters, it could be used to print just the first line. (Hint - part of your task in this question is to show that you can use the built-in Unix help facilities.)

But you really don’t want to type that command out for every file or even every directory. What command would you give to produce a listing of the names of all the text files (as absolute paths) in ~/UnixCourse or its subdirectories (possibly nested several layers deep) followed immediately by the first line of text within that file? E.g., to produce a listing looking like this:

1 Answer

3 votes

Final answer:

Use the command 'find ~/UnixCourse -name "*.txt" -type f -exec sh -c 'echo {} && head -n 1 {}' \;' to generate a listing of absolute paths for '.txt' files in the ~/UnixCourse directory and print the first line of each file.

Step-by-step explanation:

To find and display the first line of all '.txt' files within the ~/UnixCourse directory and its subdirectories, you can combine the find, xargs, and head commands in Unix. First, use find to search for files with the '.txt' extension. Then use xargs to pass the found files to the head command in order to display the first line of each file. Here is the command you could use:

find ~/UnixCourse -name "*.txt" -type f -exec sh -c 'echo {} && head -n 1 {}' \;

This command starts with find to locate files ending in '.txt'. The -name option allows you to specify the pattern for the filename, while the -type f option ensures that only files (not directories) are included. The -exec option allows you to execute another command on each file found. In this case, we are executing a small shell script that first echoes the file path (using echo {}) and then runs head -n 1 on the file to print its first line. Note that '{}' is replaced by the current file name.

User Dimas Mendes
by
8.0k points