Each names.txt line is family,given, with no commas inside either field.
Use GNU sed to output given family.
Which command is correct?
sed captures fields in parentheses and reuses them as \1 and \2 in the replacement. Swapping those references changes the order.
Detailed explanation
sed -E 's/^([^,]+),([^,]+)$/\1 \2/' names.txtIncorrect. It preserves the original family given order.
Incorrect. It preserves the original family given order.
sed -E 's/^([^,]+),([^,]+)$/\2 \1/' names.txtCorrect. It replaces the comma with a space and emits group 2 before group 1.
Correct. It replaces the comma with a space and emits group 2 before group 1.
sed 's/^([^,]+),([^,]+)$/\2 \1/' names.txtIncorrect. Without -E, these unescaped parentheses are not the intended capture groups in basic sed syntax.
Incorrect. Without -E, these unescaped parentheses are not the intended capture groups in basic sed syntax.
sed -E 's/^([^,]+),([^,]+)$/$2 $1/' names.txtIncorrect. In sed replacement text, group references use backslash notation, not shell-style $2 and $1.
Incorrect. In sed replacement text, group references use backslash notation, not shell-style $2 and $1.
Try it yourself
An example you can run in a temporary verification environment.
printf '%s\n' 'Sato,Taro' | sed -E 's/^([^,]+),([^,]+)$/\2 \1/'Expected result
Taro SatoKey points
- Parentheses capture groups
- \1 is the first group
- The replacement can reorder groups
Notes
- Environment: GNU sed 4.x / LC_ALL=C
- Command output formatting can vary slightly by distribution or tool version.
- Run the example in a temporary directory or process when possible.
Foundation review
Read the scope first
Check whether the command acts on the current shell, a new process, an existing process, or a file.
Verify the observable result
Use the supplied command and compare the output with the expected result.