[英]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 "@", eg: 我需要用“ @”替换每行的最后一个空格,例如:
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. 我试过
sed 's/ .*$/@/g' file.txt
,但.*
匹配所有内容并删除在那里找到的所有文本。
How can I replace the last space per line with "@"? 如何用“ @”替换每行的最后一个空格?
尝试这个:
sed 's/\(.*\) /\1@/'
匹配最后一个空格的正则表达式,什么都不是(?=\\S+$)
,不确定如何将sed切换到PCRE模式(以支持先行):
perl -ple "s/ (?=\S+$)/@/" file.txt
我通常为此使用Perl:
perl -ple 's/ ([^ ]+)$/@\1/' file.txt
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.