Here’s a walk-through of what that one-liner does, why each piece is there, and a couple of ideas to make it more readable / safer.
1. The idea in plain English
-
If the file already contains an “nproc” directive
(%nproc= or the older nproc= or %nprocshared=—case-insensitive)
➜ replace its numeric value with whatever is in the shell variable $nproc.
-
Else (no nproc line found)
2a. If the first line contains the word “rungauss” (old Gaussian syntax)
➜ insert a new line %nproc=$nproc right after that first line.
2b. Otherwise
➜ insert %nproc=$nproc as the new first line of the file.
2. Piece-by-piece
grep -iqE "(nproc=|%nprocshared=)" "$file" \
• grep -i -> case-insensitive
• -q -> quiet; exit status only
• -E -> extended regex
• Regex -> matches “nproc=” or “%nprocshared=”
If this grep succeeds (exit status 0) we run the first sed:
sed -i "s/[%nproc][=][0-9]*/%nproc=$nproc/I" "$file"
Problems / clarifications:
[%nproc] inside [...] actually means “any one of the characters %, n, p, r, o, c”.
That’s not the intended “literal string %nproc”.
It still works only because the first branch in the alternation was already sure the
exact string is there, so the pattern will match at the first %.
But it’s a bit accidental.
Better would be:
sed -Ei "s/(%?nproc(shared)?=)[0-9]+/\1$nproc/I" "$file"
The || { … } fallback
If the first grep fails (no nproc directive), we drop into a compound command wrapped in { … ; }
head -n 1 "$file" | grep -iq 'rungauss' && \
sed -i "/rungauss/I a %nproc=$nproc" "$file" \
|| \
sed -i "1i %nproc=$nproc" "$file"
• head -n 1 grabs the first line only.
• If that first line contains “rungauss” (case-insensitive) we append (a) a new
%nproc=$nproc line after that line.
• If not, we insert (i) the directive at the very top of the file.
3. Potential issues
- Character class bug (already noted).
- The REGEX doesn’t cover
%nprocshared= in the replacement part.
- Doesn’t guard against multiple matches per file.
- Hard to read / maintain.
4. A clearer multi-line version
#!/usr/bin/env bash
set -euo pipefail
file=$1
nproc=${2:-$(nproc)} # default to the machine’s core count
# 1. Update existing directive (if any)
if grep -qiE '(^|[^a-zA-Z])(nproc=|%nprocshared=)' "$file"; then
sed -E -i \
"s/(%?nproc(shared)?=)[0-9]+/\1${nproc}/Ig" \
"$file"
exit 0
fi
# 2. Insert a new one
if head -n1 "$file" | grep -qi 'rungauss'; then
# after first line
sed -i "1a %nproc=${nproc}" "$file"
else
# as very first line
sed -i "1i %nproc=${nproc}" "$file"
fi
5. Testing quickly
for f in sample*.gjf; do
./insert_nproc.sh "$f" 8
done
6. Takeaways
• Break complex one-liners into readable blocks.
• Use non-capturing groups, back-references (\1) and -E to keep regex precise.
• Quoting variables in sed/grep is mandatory when they may contain meta-chars.
• set -euo pipefail helps catch silent errors in scripts.
Hope that clears things up! 🚀