You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash脚本实现仅输出非空行且不使用行变量的方法

How to Filter Empty Lines in Your Bash Script Without Storing Lines in Separate Variables

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 of grep directly 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 both name and class to empty strings, this condition catches those lines and skips them with continue.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 18:27:52