//View Tip #261
Similar Tips
» Changing file extensions
» Counts files in the current directory and subdirectory
» Loop over files with spaces in the name
» My code is compiling
» Version all unversioned files in an SVN checkout

 

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


View Comments »




Comments 

Add your comment

Comments are currently disabled
Fada09
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
replace:

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

with:

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