I have directory work_dir, and there are some subdirectories inside. And inside subdirectories there are zip archives. I can see all zip archives in terminal:
find . -name *.zip
The output:
./folder2/sub/dir/test2.zip
./folder3/test3.zip
./folder1/sub/dir/new/test1.zip
Now I want to concatinate all these file names in single row with some option. For example I want single row:
my_command -f ./folder2/sub/dir/test2.zip -f ./folder3/test3.zip -f ./folder1/sub/dir/new/test1.zip -u user1 -p pswd1
In this example:
my_command
is some command
-f
the option
-u user1
another option with value
-p pswd1
another option with value
Can you help me please, how can I do this in Linux BASH ?
CodePudding user response:
This is a bash script that should do what you wanted.
#!/usr/bin/env bash
user=user1
passwd=pswd1
while IFS= read -rd '' files; do
args =(-f "$files")
done < <(find . -name '*.zip' -print0)
args=("${args[@]}" -u "$user" -p "$passwd")
printf 'mycommand %s\n' "${args[*]}"
The output should be in one-line, like what you wanted, but do change the last line from
printf 'mycommand %s\n' "${args[*]}"
into
mycommand "${args[@]}"
If you actually want to execute mycommand
with the arguments.
Change the value of user
and passwd
too.
CodePudding user response:
One way is: (updated per @M. Nejat Aydin comments)
find . -name "*.zip" -print0 | xargs -0 -n1 printf -- '-f\0%s\0' | xargs -0 -n100000 my_command -u user1 -p pswd1
Note that -n100000
parameter forces all output of the previous xargs to be executed on the same line with the assumption that number of findings will be less than 100000
.
I used null terminated versions (notice: -0
flag, -print0
) because file names can contain spaces.
CodePudding user response:
You can do this by making a bash script.
- Make a new file called whatever.sh
- Type
chmod x ./whatever.sh
so it becomes executable on the terminal - Add the BASH scripting as shown below..
#!/bin/bash
# Get all the zip files from your FolderName
files="`find ./FolderName -name *.zip`"
# Loop through the files and build your args
arg=""
for file in $files; do
arg="$arg -f $file"
done
# Run your command
mycommand $arg -u user1 -p pswd1
CodePudding user response:
$ echo mycommand $(find . -name *.zip 2>/dev/null | sed "s/^/-f /;") mycommand -f ./folder1/sub/dir/new/test.zip -f ./folder2/sub/dir/test.zip -f ./folder3/test.zip