简体   繁体   中英

BASH: The variable shows only the last line

The variable shows only the last line:

while read var1; do
    var2+="$var1"$"\n"
    if [[ $var2 == *andoi* ]]; then
        break
    fi
done < "./filename" #or other file
echo "Result:"
echo "$var2" #just read the last lines, I want all
#...edit $var2...etc...
echo "$var2" #modified

Simplified script:

while read var1; do
    var2+="$var1"$"\n"
done < "./filename" #or other file
echo "$var2" #just read the last lines, I want all
#...edit $var2...cdn...
echo "$var2" #modified

I used this http://gsteph.blogspot.com/2007/04/bash-reading-text-file.html

How do teeth variable shows all the lines in one variable?

//I corrected, it may be useful to someone.//

So you want to accumulate $var1 into $var2 ?

while read var1; do
  var2="$var2 $var1"
  # etc...
done < "./filename"

echo "$var2"

To accumulate them with a newline on each, do:

while read var1; do
  var2="$var2
$var1"
  # etc...
done < "./filename"

echo "$var2"

If you just want the contents of a file up to and including some keyword:

x=$(sed '/droid/ q')
x=$(awk '{print} /droid/ {exit}')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM