Village
Village

Reputation: 24433

How to find and replace the last space in each line of a file in BASH?

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

Answers (4)

Thijs Dalhuijsen
Thijs Dalhuijsen

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

Aprillion
Aprillion

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

Allen Luce
Allen Luce

Reputation: 8389

I usually use Perl for this:

perl -ple 's/ ([^ ]+)$/@\1/' file.txt

Upvotes: 1

Alfe
Alfe

Reputation: 59526

Try this:

sed 's/\(.*\) /\1@/'

Upvotes: 5

Related Questions