Jal*_*alT 5 sed text-processing
我有以下内容的文件。
This
is,
are,,,
a,,
Run Code Online (Sandbox Code Playgroud)
我想用单个逗号替换行尾。如果行尾没有逗号,则添加一个逗号,如果有多个逗号,则将其替换为单个逗号。
输出看起来像这样
This,
is,
are,
a,
Run Code Online (Sandbox Code Playgroud)
ter*_*don 19
最简单的方法是使用sed就地编辑:
sed -i 's/,*$/,/' file
Run Code Online (Sandbox Code Playgroud)
该-i做的更改相同的文件。您可以使用i.bak创建file.bak原始备份文件。您也可以在没有 的情况下运行它-i以在应用更改之前查看更改。该s/foo/bar/是替换操作符。它将取代的第一个实例foo用bar。该$标记行的端部,并且*是指“0或更多个”。所以,s/,*$/,/意思是“用一个逗号替换行尾的 0 个或多个逗号”。如果没有逗号,则会添加一个,如果有多个,则将它们替换为一个。
为了完成,其他一些选项:
珀尔
perl -i -pe 's/,*$/,/' file
Run Code Online (Sandbox Code Playgroud)
和sed上面一样的想法。这是从那里sed得到的-i想法。
如果速度是一个问题,这将是这里所有解决方案中最快的:
perl -i -lne 'printf join ",", (grep {$_ ne ""}split(/,/) ); print ","' file
Run Code Online (Sandbox Code Playgroud)awk
awk '{sub(/,*$/,",")}1;' file >newfile
Run Code Online (Sandbox Code Playgroud)
或者,使用较新版本的 (g)awk:
awk -iinplace '{sub(/,*$/,",")}1;' file
Run Code Online (Sandbox Code Playgroud)纯 shell(速度较慢且效率较低,仅作为示例包含在内):
while read line; do echo "${line/%,*/},"; done < file > newfile
Run Code Online (Sandbox Code Playgroud)
在${var/%foo/bar}将取代任何foo从可变的端部var与bar。在这里,我们将替换最后一个逗号之后的所有内容,因此如果每行有多个逗号,这将不起作用,它仅适用于您的 example。其他解决方案没有任何这些限制。
比sed小文件的选项慢,但在大文件上更快(在 10MB 上测试),是下面的 python 选项。
此外,如果行中其他地方可能有逗号,下面的长单行代码将起作用:
python3 -c "ls = open('file').read().splitlines(); [print( (',').join([s for s in l.split(',') if not s == ''])+',') for l in ls]"
Run Code Online (Sandbox Code Playgroud)
或者更短一点:
python3 -c "[print( (',').join([s for s in l.split(',') if not s == ''])+',') for l in open('f').read().splitlines()]"
Run Code Online (Sandbox Code Playgroud)
...'file'你的文件的绝对路径在哪里,在(单!)引号之间。
在文件上:
something like, for example this
here, read this line, I added some commas,,,,,,,,
are, you convinced or not,
just say something, anything
Run Code Online (Sandbox Code Playgroud)
...输出是:
something like, for example this,
here, read this line, I added some commas,
are, you convinced or not,
just say something, anything,
Run Code Online (Sandbox Code Playgroud)
ls = open('file').read().splitlines()
Run Code Online (Sandbox Code Playgroud)
读取文件,将其拆分为行
[s for s in l.split(',') if not s == '']
Run Code Online (Sandbox Code Playgroud)
用分隔符分割行从行尾,删除(可能的)逗号
(',').join([s for s in l.split(',') if not s == ''])+','
Run Code Online (Sandbox Code Playgroud)
连接拆分部分,在末尾添加逗号。