How to remove the last character from all lines bu

2019-09-09 04:10发布

问题:

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

回答1:

You can use sed for this:

$ 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.



回答2:

An awk version:

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


标签: linux string sed