//View Tip #261
Similar Tips
» Changing file extensions
» Checksum directory recursively
» Disable bash history
» Filter stderr for cron jobs
» My code is compiling


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

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"

View Comments »


Add your comment

Comments are currently disabled
For us, on Solaris OS, we need to change "let i++" by "i=$(expr $i + 1)"

Except that excellent tip :-)
Posted 2008-10-15 14:04:26

numberoflines=$(cat mytextfile.txt | wc -l)


numberoflines=$(wc -l < mytextfile)

saves you a cat
Posted 2009-02-19 21:31:44

Home Latest Browse Top 25 Random Hall Of Fame Contact Submit