如何将Bash命令输出结果的最后一个逗号替换为句号?
Great question! To replace the trailing comma with a period, you just need to add one more sed command to your existing pipeline to target the last occurrence of the comma-space pair. Here's how to adjust your script:
Modified Script
export FT_LINE1=13 FT_LINE2=23; cat /etc/passwd | grep -v "#" | awk 'NR%2==1' | cut -f1 -d":" | rev | sort -r | awk -v l1="$FT_LINE1" -v l2="$FT_LINE2" 'NR>=l1 && NR<=l2' | tr '\n' ',' | sed -e 's/, */, /g' -e 's/, $/. /'
What Changed?
I made two small but impactful adjustments:
- Combined the
exportcommands into a single line for cleaner, more concise syntax (optional but easier to read). - Added a second
sedcommand (s/, $/. /) that specifically targets the trailing,(comma followed by space) at the end of the line and replaces it with.(period followed by space).
Breakdown of the Final Sed Commands:
s/, */, /g: Ensures all elements are separated by a consistent,(comma + space) by replacing any messy sequence of commas and/or spaces with this clean pattern.s/, $/. /: Matches only the,at the very end of the line (the$anchors the match to the line's end) and swaps it for the desired..
Alternative Approach (Simpler Pipeline with awk)
If you want to streamline things further, you can use awk to handle both the line range filtering and the final joining in one step, which eliminates the need for tr and multiple sed calls:
export FT_LINE1=13 FT_LINE2=23; cat /etc/passwd | grep -v "#" | awk 'NR%2==1' | cut -f1 -d":" | rev | sort -r | awk -v l1="$FT_LINE1" -v l2="$FT_LINE2" 'NR>=l1 && NR<=l2 { arr[++n] = $0 } END { for (i=1; i<n; i++) printf "%s, ", arr[i]; printf "%s.\n", arr[n] }'
This builds an array of your matching lines, then prints all but the last element with , , followed by the last element with a . at the end—no extra cleanup needed.
Either approach will give you the exact output you're looking for!
内容的提问来源于stack exchange,提问作者Gabe Spound

