Bash脚本实现仅输出非空行且不使用行变量的方法
Got it, let's tweak your script to skip empty lines while keeping your existing field-processing logic intact—no need for a separate variable to hold each full line. Here are two clean, straightforward approaches:
Option 1: Pre-Filter Empty Lines with grep
Use grep -v '^$' to strip out empty lines before feeding the file into your read loop. This keeps your loop logic simple since you only process non-empty lines right from the start.
Here's the modified script:
while IFS=: read -r name class; do # Keep your existing formatting logic here (adjust the echo to match your needs) echo "Name: $name | Class: $class" done < <(grep -v '^$' /home/user/scripte/schuelerListe.txt)
- The
<(...)syntax is process substitution—it lets us pass the filtered output ofgrepdirectly to the loop without spawning a subshell (useful if you ever need to modify variables inside the loop later). grep -v '^$'targets lines that are NOT (-v) empty (^$means start-of-line to end-of-line with nothing in between).
Option 2: Skip Empty Lines Inside the Loop
If you prefer not to use an extra grep process, add a quick check inside the loop to skip lines where both fields are empty (which is exactly what happens when reading a blank line):
while IFS=: read -r name class; do # Skip lines where both name and class are empty (i.e., empty lines) [[ -z "$name" && -z "$class" ]] && continue # Your existing formatting logic stays here echo "Name: $name | Class: $class" done < /home/user/scripte/schuelerListe.txt
[[ -z "$var" ]]checks if a variable is empty. Since a blank line sets bothnameandclassto empty strings, this condition catches those lines and skips them withcontinue.
Example Output
If your schuelerListe.txt looks like this:
Lena:10C Jonas:9B Mia:11A
Both scripts will output:
Name: Lena | Class: 10C Name: Jonas | Class: 9B Name: Mia | Class: 11A
内容的提问来源于stack exchange,提问作者toni

