Reputation: 24433
I have a file like this:
Once upon a time there lived a cat.
The cat lived in the forest.
The forest had many trees.
I need to replace the last space per line with a "@", e.g.:
Once upon a time there lived a@cat.
The cat lived in the@forest.
The forest had many@trees.
I tried sed 's/ .*$/@/g' file.txt
, but .*
matches everything and deletes all of the text found there.
How can I replace the last space per line with "@"?
Upvotes: 3
Views: 2177
Reputation: 778
Try
s/\s([^\s]*)$/@\1/g
Good luck, bob
EDIT: lol, tested it, seems to do what you want :)
my $s = "the quick brown fox jumped";
$s =~ s/\s([^\s]*)$/@\1/g;
print $s;
# prints the quick brown fox@jumped
Upvotes: 1
Reputation: 22340
The regex to match the last space and nothing else is (?=\S+$)
, not sure how to switch sed into PCRE mode (to support lookaheads):
perl -ple "s/ (?=\S+$)/@/" file.txt
Upvotes: 3
Reputation: 8389
I usually use Perl for this:
perl -ple 's/ ([^ ]+)$/@\1/' file.txt
Upvotes: 1