1

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.

6
  • I think you'll probably need to use mktemp and then rename once you've parsed the output. Commented Aug 9, 2019 at 23:51
  • Hard to understand exactly what you need, but why not n=$(ls -1 *.mp4 | wc -l); touch "$n-mp4"? (or ...; echo "$n" > "$n-mp4") Commented Aug 10, 2019 at 0:24
  • @AaronD.Marasco i think the mv command suggested by alexbclay did the rename you mentioned and changed its name based on the tail of the file contents. Commented Aug 10, 2019 at 1:09
  • @DavidC.Rankin not sure if you got my question but the ls command didn't work for me as it didn't find any files with an extension of mp4 (not sure if it's distro related or not) Commented Aug 10, 2019 at 1:10
  • @John13 -- if your files reside in subdirectories, then ls will not work. (not without adjusting globstar in bash, etc..) and find is the proper tool. Which you can change to n=$(find . -type f -name *.mp4 | wc -l); echo "$n" > "$n-mp4"; unset n Commented Aug 10, 2019 at 8:00

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Awesome that worked, now i'm trying to understand why it works :)
Figured it out! the and operand just adds another command to run instead of the output and move is used to rename the file from its contents using the evaluation of the tail command's output of the file contents, very clever actually and i really learned a lot of shell here, although i found many people saying $() should be used instead of backticks for eval
Thanks for the answer and clarification @alexbclay
If you already have a file named filename, it's in trouble. That's why I mentioned mktemp.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.