Skip to content

run a command with a file pattern

I have this file patterns.txt

a
b
c
d
e

And I want to run a specific command for every pattern like this:

scp username@hostname:/name/a
scp username@hostname:/name/b
scp username@hostname:/name/c
scp username@hostname:/name/d
scp username@hostname:/name/e

I tried to used for loop like this:

#!/bin/bash
cat pattern.txt
for i in $pattern.txt
do
scp username@hostname:/name/$i
done

but i didn’t work

Advertisement

Answer

The 2 typical approaches are:

while read i; do 
scp username@hostname:/name/"$i"
done < patterns.txt

and

sed 's#^#username@hostname:/name/#' patterns.txt | xargs -L 1 scp 

Note that I would expect both of those to fail, since scp expects at least 2 arguments. How you want that 2nd argument to fit in the command you run will change how you can use xargs for this.

For example, if you want to execute scp username@hostname:/name/a ., you could do:

sed 's#^#username@hostname:/name/#' patterns.txt |
xargs -L 1 -J % scp % . 

You can also do for i in $(cat patterns.txt), but you shouldn’t.

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