Or a very close, but whitespace agnostic substitution with sed
using the [[:space:]]
list in character-class to handle the whitespace regardless of whether it is ' '
, or '\t'
or mixed using sed
with the extended REGEX option would be:
sed -E 's/^([^[:space:]]+)[[:space:]]+(.*$)/\2 [\1]/' file
If your sed
doesn't support extended regex (and doesn't use the -r
option instead of -E
for it), then you can do it with standard set regex by escaping the '('
and ')'
backreference capture delimiters, e.g.
sed 's/^\([^[:space:]][^[:space:]]*\)[[:space:]][[:space:]]*\(.*$\)/\2 [\1]/' file
(note: standard regex doesn't support the '+'
, one-or-more occurrence, repetition operator so the '*'
zero-or-more repetition is used requiring one literal match also be included to create the equivalent one-or-more repetition match.)
In both cases the standard substitution form is 's/find/replace/
shown with Extended REGEX below where:
find:
^
anchors the search at the beginning of line,
([^[:space:]]+)
captures all (one-or-more) characters from the beginning that are not whitespace (the '^'
in the character-class inverts the match) for use as the 1st backreference,
[[:space:]]+
select one or more spaces,
(.*$)
capture all remaining characters to '$'
(end of line) for the 2nd backreference.
replace
\2
insert the text captured as the 2nd backreference,
' '
insert a space, and finally,
\1
insert the text captured as the 1st backreference.
Example Use/Output
$ sed -E 's/^([^[:space:]]+)[[:space:]]+(.*$)/\2 [\1]/' << 'eof'
id1 str1 str2 .. strn
id2 str1 str2 .. strm
eof
str1 str2 .. strn [id1]
str1 str2 .. strm [id2]
Let me know if you have questions.