1
#! /bin/bash
for i in {A,B,C,D,E,F,G,H,J} ; do

     echo     "$i
               $i
               $i
               $i 
               $i
               $i
               $i
               $i"
    cat > ~/Desktop/$i.txt                    
done

I want to make 9 text files, each showing me one letter repeated 8 times. e.g. A.txt should have the letter A 8 times in a column) If I run the script without the cat, it indeed shows me 8 times the A letter, then 8 times the B, C, etc. When inserting the cat statement, it doesn't work. What am I doing wrong?

  • cat is expecting an input, but echo command isn't redirected to cat. – Archemar Oct 27 '16 at 14:30
  • ergo: just leave out the cat statement and put the echo statement and the redirection operator (>) into a single line. – user236012 Oct 27 '16 at 14:42
  • like this: echo "$i $i $i $i $i $i $i $i" > ~/Desktop/$i.txt – user236012 Oct 27 '16 at 14:45
1

They're two independent commands.

echo something
cat > somewhere

You can use pipe to pass the stdout to stdin:

echo something | cat > somewhere
  • While he is trying to use it and I understand why you have it in your answer, It may also be useful to point out that cat is unnecessary in this scenario. i.e. echo something > somewhere – Zachary Brady Oct 27 '16 at 14:18
  • He already wrote that without cat command it works as he expected. – Ipor Sircer Oct 27 '16 at 14:22
1

A simple solution to this would be a double for loop as follow:

for f in {A..J}; do for ((i=0;i<8;i++)); do printf '%s\n' "$f" >> "$f"; done; done
1

You can use bash sequences for the loop and clever use of printf to repeat characters:

for i in {A..J};do printf "$i%.0s\n" {0..7} > ~/Desktop/$i.txt;done
1

As Ipor Sircer pointed out you are just missing a pipe between your echo and cat. Another solution would be to use yes to repeat the same text of multiple lines and head instead of cat to limit the number of lines, e.g.

for i in {A..J}
do
   yes -- "$i" | head -8 >  ~/Desktop/"$i".txt
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.