I have to replace the last word from each line with the first one. The code is:
$ sed "s/\(^a-z,0-9]*\)\(.*\)\([a-z,0-9]*$\)/\1\2\1\g".
I don't understand this part
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It only takes a minute to sign up.Sign up to join this community
After correcting the basic syntax mistakes, you have:
\(^[a-z,0-9]*\)save any number of lowercase letters or numbers at the start of the line (
^is start of line) for later (reference later with
\(.*\)Save any number of any characters for later (to reference as
\([a-z,0-9]*$\)save any number of lowercase letters or numbers at the end of the line (
$is end of line) for later (reference as
\1\2\1print the first pattern, then the second, then the first again
gthis is inappropriate in this expression. It means act on multiple matches on the same line, but our expression has to read the whole line, so
gmakes no sense and should be omitted.
This still will not work, because regular expressions are greedy, so the middle
\(.*\) matches everything after the first word, resulting in the first word being reprinted at the end of the line without replacing anything.
You could fix it (also adding
I for case-insensitive search):
sed "s/\(^[a-z,0-9]*\) \(.*\) \([a-z,0-9]*$\)/\1 \2 \1/I"
If you wanted to include other characters besides letters and numbers:
sed -r 's/^([^ ]+) (.*) ([^ ]+)$/\1 \2 \1/'
-ruse ERE (saves using all those backslashes)
[^ ]+at least one of any characters except spaces
I don't think your code is even going to work here because it's simply malformed. I'd rewrite the entire expression. Assuming that all lines begin and end with words that contain only numbers and letters from the alphabet, you could try this:
$ echo -en "foo bar baz\nThe Good, the Bad and the Ugly\n" | \ > sed 's/^\(\<[[:alpha:]]\+\>\)\(.*\)\<[[:alpha:]]\+\>$/\1\2\1/g' foo bar foo The Good, the Bad and the The
s/PATTERN/SUBSTITUTION_STRING/g - PATTERN is what we're looking for and SUBSTITUTION_STRING is what we're going to substitute said pattern with.
g means that the entire line will be scanned as opposed to going only for the first match found on the line.
^\(\<[[:alpha:]]\+\>\) - if a line begins with a word boundary that's followed by more than one alphanumeric character followed by another word boundary, save all that in the variable
\<[[:alpha:]]\+\>$ - the same exact thing here, but we are only using this to identify the location of the last word.
\(.*\) - anything in between will be saved in the variable
\1\2\1 - the same line with the last word replaced with the first one.