如何从所有行中删除最后一个字符,但仅限于它是某个特定字符

时间:2022-03-26 09:27:16

i have data in this form

我有这种形式的数据

Kure|Hiroshima
Kure|Hiroshima
Kure|Hiroshima
NO MATCHING
Aachen|
Darmstadt
Mulheim
Aachen|

and i want to remove the last character only if it is a pipe (|).

我想删除最后一个字符,如果它是一个管道(|)。

desired output

期望的输出

Kure|Hiroshima
Kure|Hiroshima
Kure|Hiroshima
NO MATCHING
Aachen
Darmstadt
Mulheim
Aachen

Thanks in advance

提前致谢

2 个解决方案

#1


1  

You can use sed for this:

你可以使用sed:

$ sed 's/|$//' file
Kure|Hiroshima
Kure|Hiroshima
Kure|Hiroshima
NO MATCHING
Aachen
Darmstadt
Mulheim
Aachen

It looks for | together with $ (which means "end of line") and deletes it.

它寻找|与$(表示“行尾”)一起删除它。

Note you can use sed -i in case you want to do an in-place edit.

请注意,如果要进行就地编辑,可以使用sed -i。

#2


0  

An awk version:

一个awk版本:

awk '{sub(/\|$/,"")}1' file

#1


1  

You can use sed for this:

你可以使用sed:

$ sed 's/|$//' file
Kure|Hiroshima
Kure|Hiroshima
Kure|Hiroshima
NO MATCHING
Aachen
Darmstadt
Mulheim
Aachen

It looks for | together with $ (which means "end of line") and deletes it.

它寻找|与$(表示“行尾”)一起删除它。

Note you can use sed -i in case you want to do an in-place edit.

请注意,如果要进行就地编辑,可以使用sed -i。

#2


0  

An awk version:

一个awk版本:

awk '{sub(/\|$/,"")}1' file