Home > Mobile >  How to join the output of two commands when using find -exec?
How to join the output of two commands when using find -exec?

Time:01-27

I have the following code:

find . -exec stat --format='%n,%x,%y,%z,' \; 2>&1 | tee output_sasdata_file_info.txt

I wanted the du -k command to be executed and saved to the txt right after the %z,

Tried doing it like this but it's just running the du -k command and ignoring the stat

find . -exec stat --format='%n,%x,%y,%z' find . -exec du -k,; \; 2>&1 | tee output_sasdata_file_info.txt

Example of desired output:

./sas/anual.sas7bdat.gz,2020-03-04 11:21:59.648155603 -0300,2020-03-04 11:21:59.845155836 -0300,2021-02-01 16:40:26.542568391 -0350,2656546

CodePudding user response:

If you want to run two commands whose output is combined into a single line, you'll need to use -exec to execute a single shell that runs both commands.

find . -exec sh -c \
  'for f; do stat --format="%n,%x,%y,%z,$(du -k "$f")" "$f"; done' \
  _ {}  

Some notes of explanation:

  1. When using -c, the first argument following the shell command is used to set $0. I usually use a dummy value of _ when I don't care what $0 is set to.
  2. -exec ... {} will pass as many matches as possible to the command being run.
  3. The loop in the -c argument iterates over the files passed to the shell by find in this invocation.
  4. du -k "$f" is run first to construct the format string to be used when stat ... "$f" is called. (I am assuming that the argument to du will be a single file, not a directory, as otherwise you are going to get a list of results that won't fit nicely into the line you are trying to construct.)

CodePudding user response:

This version works on my computer:

find . -exec stat --printf='%n,%x,%y,%z,' {} \; -exec du -k {} \; 2>&1 | tee output_sasdata_file_info.txt

Use the --printf option for stat to print the lines without the trailing newline character.

  •  Tags:  
  • Related