Hey I have a question.
This is the command that I'm using (at the place of echo $file is a different command. I simplified it):
find /home/cas/plex-media/series/ -type f -name "*" ! -name "*.srt" -print0 | sort | xargs -0 -n1 -I{} file={} && echo $file
It says that file={} isn't a command, which is true because it is a variable. I need to set that variable to one line of the output each time, just as xargs does with a command. But I need it to fill the variable and then run that command with that variable for each line of the ouput of sort.
Example:
As input (aka ouput of sort):
/home/cas/plex-media/series/Pokémon/Season 1/Pokémon - S01E01 - Pokémon - I Choose You!.mp4
/home/cas/plex-media/series/Pokémon/Season 1/Pokémon - S01E02 - Pokémon Emergency.mp4
/home/cas/plex-media/series/Pokémon/Season 1/Pokémon - S01E03 - Ash Catches a Pokémon.mp4 How I want it to be executed every time by xargs:
file=/home/cas/plex-media/series/Pokémon/Season 1/Pokémon - S01E01 - Pokémon - I Choose You!.mp4 && echo /home/cas/plex-media/series/Pokémon/Season 1/Pokémon - S01E01 - Pokémon - I Choose You!.mp4
file=/home/cas/plex-media/series/Pokémon/Season 1/Pokémon - S01E02 - Pokémon Emergency.mp4 && echo /home/cas/plex-media/series/Pokémon/Season 1/Pokémon - S01E02 - Pokémon Emergency.mp4
file=/home/cas/plex-media/series/Pokémon/Season 1/Pokémon - S01E03 - Ash Catches a Pokémon.mp4 && echo /home/cas/plex-media/series/Pokémon/Season 1/Pokémon - S01E03 - Ash Catches a Pokémon.mp4I can't just do echo {} as I have multiple places is my command where {} needs to be filled in and I have quite alot of command {} $(other command {}). So I replaced all those places where the output of sort needs to go with the variable $file. Because then xargs only needs to change the variable once and run the command. Then change the variable and run the command again etc etc.
I hope that you understand my problem and what my goal is. Can you help me?
Thanks!
21 Answer
Use xargs with sh -c (orbash -c if needed):
find ... -print0 | sort -z | xargs -0 -n1 -I{} sh -c 'file=$1; echo "$file";' xargs-sh {}If you don't need the sort step, better avoid xargs and use find -exec :
find /home/cas/plex-media/series/ -type f ! -name "*.srt" \ -exec sh -c 'file=$1; echo "$file";' find-sh {} \;For why we need this strange notation sh -c '...' sh {} , please see Is it possible to use find -exec sh -c safely?