Skip to content
Advertisement

Create filename based on file output in shell

I’m looking to create files with names based on the command output of the previous command i.e. if i run

find . -name *.mp4 | wc -l > filename

So that the output of the amount of files of that type is the filename of the created file.

Advertisement

Answer

Here’s a solution that renames the file after it has been created:

find . -name *.mp4 | wc -l > filename && mv filename `tail -n 1 filename`

What is happening in this one-liner:

find . -name *mp4 | wc -l > filename : Finds files with mp4 suffix and then counts how many were found and redirects the output to a file named filename

tail -n 1 filename: Outputs the very last line in the file named filename. If you put backticks around it (`tail -n 1 filename`) then that statement is executed and replaced by the text it returns.

mv filename `tail -n 1 filename`: Renames the original file named filename to the executed statement above.

When you combine these with &&, the second statement only runs if the first was successful.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement