Reading a variable line by line with while loop

James Michael Fultz croooow at gmail.com
Tue Dec 1 22:34:19 UTC 2009


* Ray Parrish <crp at cmc.net> [2009-12-01 09:42 -0800]:
> I like the fact that it only took three lines of code to sort that out 
> and reduce the redundancy, but I have decided the order of the original 
> bash history is important, and am working on a way to test each line as 
> read in the loop to see if it already exists in the variable.
> 
> I need to complete the following if statement somehow.
> 
> BashHistory=`cat ~/.bash_history`
> echo "$BashHistory" | (while read ThisCommand; do
>       ThisCommand=${ThisCommand// /__};
>       # If this input string does not already exist in $History
>       if [ ! $ThisCommand in $History ]
>          then
>                 History="$History $ThisCommand";
>       fi
>  done;
> echo "History - $History")

If you don't need to reuse your variables later, this should run faster.

awk '
        END {
                print "History - "
                for (k in a) {
                        gsub(/ /, "__", k); print k
                }
        }
        { a[$0] }' \
                ~/.bash_history

> Anyway, that's what I'm working on now, so thanks again for all the help 
> you people have been being for this novice bash scripter. 8-)
> 
> Later, Ray Parrish




More information about the ubuntu-users mailing list