我有一些字符串:
示例输入:
Also known as temple of the city,
xxx as Pune Banglore as kolkata Delhi India,
as Mumbai India or as Bombay India,
Calcutta,India is now know as Kolkata,India,
从上面我想将转换为xxx xxxx xx,转换为作为xxx_xxxx_xx,,它应该在最后之后生效为。
上面的示例输出:
Also known as temple_of_the_city,
xxx as Pune Banglore as kolkata_Delhi_India,
as Mumbai India or as Bombay_India,
Calcutta,India is now know as Kolkata,India,
在一行中最后一个为后,不应有空格分隔的字符串。
如果不清楚,请告诉我。 感谢
答案 0 :(得分:2)
保罗是对的,这不是一项简单的任务。这是我放在一起的sed
解决方案:
sed 's/\(.*as \)/\1\n/;h;y/ /_/;G;s/.*\n\(.*\)\n\(.*\)\n.*/\2\1/' file.txt
对您的数据进行演示:
$ echo 'Also known as temple of the city,
> xxx as Pune Banglore as kolkata Delhi India,
> as Mumbai India or as Bombay India,
> Calcutta,India is now know as Kolkata,India,' | \
> sed 's/\(.*as \)/\1\n/;h;y/ /_/;G;s/.*\n\(.*\)\n\(.*\)\n.*/\2\1/'
Also known as temple_of_the_city,
xxx as Pune Banglore as kolkata_Delhi_India,
as Mumbai India or as Bombay_India,
Calcutta,India is now know as Kolkata,India,
答案 1 :(得分:1)
我倾向于使用瑞士军用电锯Perl,但是sed也是一种选择。在任何一种情况下,你都在寻找一个实质性的学习曲线。
你所描述的替代品可能很复杂,你最好不要写一个剧本,而不是试图把它作为一个班轮。
如果你要编写一个脚本并且还不知道Perl,那么只要它有某种文本模式,就没有理由不选择你选择的脚本语言(python,ruby等)。匹配语法。
我不知道一种简单,浅薄的学习曲线方法,可以进行复杂的模式匹配和替换。这是一次性的事情,你只需要做这个替换吗?或者您将来会做类似的复杂模式替换。如果你经常这样做,你真的应该花时间学习一些脚本语言,但我不会强加你的Perl偏见。只需挑选任何看似可访问的语言。