//View Tip #261
» Command line currency conversion
» Find files greater than a certain size
» Bash function to decompress archives
» list the most recent files in a directory
Similar Tips
» Reverse geocode with bash» Command line currency conversion
» Find files greater than a certain size
» Bash function to decompress archives
» list the most recent files in a directory
Latest tips by RSS
Click here to subscribe
Follow Shell-Fu on Twitter
Click here to follow
Follow Shell-Fu on identi.ca
Click here to follow
The for loop has a problem with entries with spaces, whether it's file names or entries in a text file. Common solutions include changing the IFS variable to exclude spaces (so that the for loop will only use tabs and line breaks to separate entries) and piping the entries to a 'while read line; do' command. However, setting and resetting IFS each time you want to include/exclude spaces is kinda messy and the 'while read' thing means you can't make any normal use of the read command within the loop. For a once-per-line loop that doesn't present these problems, try
i=0
numberoflines=$(cat mytextfile.txt | wc -l)
while [ $i -lt $numberoflines ]; do
let i++
contentoflinenumberi="$(sed -n ${i}p mytextfile.txt)"
read -p "Do you wish to see line ${i}? (y/n) " reply
if [ "$reply" = "y" ]; then
echo "$contentoflinenumberi"
fi
done
Comments
Add your comment
Comments are currently disabled
replace:
numberoflines=$(cat mytextfile.txt | wc -l)
with:
numberoflines=$(wc -l < mytextfile)
saves you a cat
numberoflines=$(cat mytextfile.txt | wc -l)
with:
numberoflines=$(wc -l < mytextfile)
saves you a cat
Posted 2009-02-19 21:31:44


Except that excellent tip :-)