Using 'if' within a 'while' loop in Bash
54,681
Solution 1
You should be checking for >
, not <
, no?
while read line; do
if [[ $line =~ ">" ]]; then
echo $line
fi
done < /tmp/voo
Solution 2
Do you really need regex here? The following shell glob can also work:
while read line; do [[ "$line" == ">"* ]] && echo "$line"; done < /tmp/voo
OR use AWK:
awk '/^>/ { print "processing: " $0 }' /tmp/voo
Solution 3
grep
will do:
$ grep -oP '> \K\w+' <<END
18633a18634
> sashabrokerSTP
18634a18636
> sashatraderSTP
21545a21548
> yheemustr
END
sashabrokerSTP
sashatraderSTP
yheemustr
Author by
capser
Updated on August 10, 2020Comments
-
capser over 3 years
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 apparentlywhile
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$