UNIX循环中If语句未排除目标变量,海冰文件合并重复问题求助
Hey there! Let's troubleshoot why your loop isn't excluding the 1979 and 1980 files, and fix that duplicate entry issue once and for all.
First, let's break down the common reasons your if statement might be failing to skip those two years:
- Incorrect comparison syntax: Bash treats
=as a string comparison operator, while-eqis for numeric comparisons. While both work for integer years, mixing up syntax or missing proper spacing can break the check. - Faulty logical operator placement: If you tried to cram both conditions into a single
[ ]without proper syntax (like[ $year = 1979 || $year = 1980 ]), that's invalid bash syntax and will be ignored. - Unquoted variables: If for some reason your
yearvariable had unexpected whitespace (unlikely here, but still a good habit), unquoted variables can cause the condition to evaluate incorrectly.
Fix 1: Skip the problem entirely by narrowing your loop range
The simplest solution is to start your loop at 1981 instead of 1979, so you never have to exclude the first two years in the first place. Here's how that looks:
#!/bin/bash # Merge the first two years first cat seaice_1979.txt seaice_1980.txt > combined_seaice.txt # Loop only through 1981-2015 to avoid duplicates for year in {1981..2015} do cat "seaice_$year.txt" >> combined_seaice.txt done
Fix 2: Correct the if statement logic
If you need to keep the full 1979-2015 loop range (for example, if your file naming is more dynamic), fix the condition check with proper bash syntax. Here are two reliable ways:
Option A: Use numeric comparison with -eq
#!/bin/bash cat seaice_1979.txt seaice_1980.txt > combined_seaice.txt for year in {1979..2015} do # Proper numeric check with quoted variable to avoid edge cases if [ "$year" -eq 1979 ] || [ "$year" -eq 1980 ]; then continue # Skip to next iteration fi cat "seaice_$year.txt" >> combined_seaice.txt done
Option B: Use [[ ]] for cleaner logical syntax
The double bracket [[ ]] is a bash extension that allows more natural logical operations inside the condition:
#!/bin/bash cat seaice_1979.txt seaice_1980.txt > combined_seaice.txt for year in {1979..2015} do if [[ "$year" == 1979 || "$year" == 1980 ]]; then continue fi cat "seaice_$year.txt" >> combined_seaice.txt done
Bonus: Even simpler one-liner merge
If you don't need the separate "merge first two years" step (just need all files combined once), you can use bash brace expansion to do it in a single command, no loops required:
cat seaice_1979.txt seaice_1980.txt seaice_{1981..2015}.txt > combined_seaice.txt
Any of these approaches should eliminate the duplicate entries from 1979 and 1980. Let me know if you need to adjust this for your specific file naming structure!
内容的提问来源于stack exchange,提问作者Kirby McErlane Bartlett

