String set for a for loop using pipe (shell script)

Asked

Viewed 44 times

0

I’m trying to write a shell script that processes some strings and passes them all by pipe to a for loop, but I’m having trouble getting the iterator through those strings, because I thought that using $* would work. The goal is to be able to create several subfolders with the name of each string.

for i in $(seq 1 30); do 
    cat /dev/urandom | tr -cd 0-9 | head -c 8 ; echo ;
done | 
sed 's/\([[:digit:]]\{3\}\)\([[:digit:]]\{5\}\)/\1-\2/' | 
tr '\n' ' ' | for folder in $*; do mkdir diretorio/$folder ; done

1 answer

0


You can use a temporary file for this.

#!/bin/bash
TEMP_FILE=/tmp/tabela

for i in $(seq 1 30); do
    cat /dev/urandom | tr -cd 0-9 | head -c 8 ; echo ;
done |
    sed 's/\([[:digit:]]\{3\}\)\([[:digit:]]\{5\}\)/\1-\2/'  > $TEMP_FILE

IFS='
'
for LINE in $(cat $TEMP_FILE)
do
        mkdir diretorio/$LINE
done

Using xargs, it is possible to make directly

#!/bin/bash
cd diretorio
for i in $(seq 1 30); do
    cat /dev/urandom | tr -cd 0-9 | head -c 8 ; echo ;
done |
    sed 's/\([[:digit:]]\{3\}\)\([[:digit:]]\{5\}\)/\1-\2/'  | xargs -L1 mkdir
  • It was kind of the solution that ended up leaving me, but I thought there would be some more direct way

Browser other questions tagged

You are not signed in. Login or sign up in order to post.