[英]How to replace the nth space before a string on each line in a file using sed
[英]How to find and replace the last space in each line of a file in BASH?
我有一个这样的文件:
Once upon a time there lived a cat.
The cat lived in the forest.
The forest had many trees.
我需要用“ @”替换每行的最后一个空格,例如:
Once upon a time there lived a@cat.
The cat lived in the@forest.
The forest had many@trees.
我试过sed 's/ .*$/@/g' file.txt
,但.*
匹配所有内容并删除在那里找到的所有文本。
如何用“ @”替换每行的最后一个空格?
尝试这个:
sed 's/\(.*\) /\1@/'
匹配最后一个空格的正则表达式,什么都不是(?=\\S+$)
,不确定如何将sed切换到PCRE模式(以支持先行):
perl -ple "s/ (?=\S+$)/@/" file.txt
我通常为此使用Perl:
perl -ple 's/ ([^ ]+)$/@\1/' file.txt
尝试
s/\s([^\s]*)$/@\1/g
祝你好运,鲍勃
编辑:哈哈,测试它,似乎做你想要的:)
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.