1

The following cat command seems to work fine outside the for loop but when I place it inside of it gives a syntax error:

for i in 1 2 3 4 5 do
  cat file_$i | grep "random text" | cut -d':' -f2 > temp_$i
done

Could someone explain to me the correct way to write this? Thank you

2
  • What's the error it gives? Also, grep can take a file as an argument so you don't have to cat a file and pipe it to it. Commented May 12, 2015 at 2:27
  • "Syntax error near unexpected token 'cat' " Commented May 12, 2015 at 2:28

4 Answers 4

5

Your for loop should have a semicolon:

for i in 1 2 3 4 5; do
Sign up to request clarification or add additional context in comments.

1 Comment

Or put do on the next line.
2

You don't need to put 1 2 3 4 5 to loop through.

You can use bash brace expansion. {1..5}

for i in {1..5}; do 
##
done

Comments

1

I always prefer put "do" in the next line, this way helps me to don't remember use semicolons:

for i in 1 2 3 4 5
do
  cat file_$i | grep "random text" | cut -d':' -f2 > temp_$i
done

Comments

1

In bash, the 'end of the line' is implicitly considered as end of commands/statements by bash compiler.

Example:

echo "Hello"
exit
#No need of semi-colons here as it is implicit that the end of the line is the completion of the statement 

But when you want to add two statements/commands on the same line, you need to separate them by semi-colon (;) explicitly.

Example:

   echo "hello"; exit
#here semi-colon implies that the echo statement ends at the semi-colon and from there on to the end of the line is a new statement.

With respect to "for statement", the syntax goes as:

for variable in (value-set)
do
 ----statements----
done

So, either you put the for, do , statements and done in new line or separate them by semi-colons.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.