Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using 'if' within a 'while' loop in Bash

I have these diff results saved to a file:

bash-3.00$ cat /tmp/voo
18633a18634
> sashabrokerSTP
18634a18636
> sashatraderSTP
21545a21548
> yheemustr

I just really need the logins:

bash-3.00$ cat /tmp/voo | egrep ">|<"
> sashaSTP
> sasha
> yhee
bash-3.00$

But when I try to iterate through them and just print the names I get errors. I just do not understand the fundamentals of using "if" with "while loops". Ultimately, I want to use the while loop because I want to do something to the lines - and apparently while only loads one line into memory at a time, as opposed to the whole file at once.

bash-3.00$ while read line; do  if [[ $line =~ "<" ]] ; then  echo $line ; fi ;  done <  /tmp/voo
bash-3.00$
bash-3.00$
bash-3.00$ while read line; do  if [[ egrep "<" $line ]] ; then  echo $line ; fi ;  done    <  /tmp/voo
bash: conditional binary operator expected
bash: syntax error near `"<"'
bash-3.00$
bash-3.00$ while read line; do  if [[ egrep ">|<" $line ]] ; then  echo $line ; fi ;  done <  /tmp/voo
bash: conditional binary operator expected
bash: syntax error near `|<"'
bash-3.00$

There has to be a way to loop through the file and then do something to each line. Like this:

bash-3.00$ while read line; do  if [[ $line =~ ">" ]];
 then echo $line |  tr ">" "+" ;
 if [[ $line =~ "<" ]];
 then echo $line | tr "<" "-" ;
 fi ;
 fi ;
 done  < /tmp/voo


+ sashab
+ sashat
+ yhee
bash-3.00$
like image 752
capser Avatar asked Dec 03 '13 19:12

capser


People also ask

Can we use for loop inside if statement in shell script?

You should be using a while loop, instead of a for loop in this case, as the for loop will break if any of the filenames contain spaces or newlines. Also, the test command you have issued will also give a syntax error if the glob expands to multiple files.

What is while IFS in bash?

The special shell variable IFS determines how Bash recognizes word boundaries while splitting a sequence of character strings. The default value of IFS is a three-character string comprising a space, tab, and newline: $ echo "$IFS" | cat -et ^I$ $

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

Can you have multiple if statements in bash?

Bash else-if statement is used for multiple conditions. It is just like an addition to Bash if-else statement. In Bash elif, there can be several elif blocks with a boolean expression for each one of them. In the case of the first 'if statement', if a condition goes false, then the second 'if condition' is checked.


1 Answers

You should be checking for >, not <, no?

while read line; do
    if [[ $line =~ ">" ]]; then
        echo $line
    fi
done < /tmp/voo
like image 67
John Kugelman Avatar answered Sep 22 '22 08:09

John Kugelman