Skip to content
Advertisement

Replace characters on specific location every line

We got an exercise where we have to do certain things with the following text document:

Rank|Mountain|Height (m)|Height (ft)|Prominence (m)|Range|Coordinates|Parent mountain|First ascent|Ascents (failed attempts)|Country
1|Mount Everest/Sagarmatha/Chomolungma|8,848|29,029|8,848|Mahalangur Himalaya|27°59'17"N 86°55'31"E|none|1953|>>145 (121)|Nepal/China
2|K2/Qogir/Godwin Austen|8,611|28,251|4,020|Baltoro Karakoram|35°52'53"N 76°30'48"E|Mount Everest|1954|45 (44)|Pakistan/China
...
40|Gangkhar Puensum|7,570|24,836|2,995|Kula Kangri Himalaya|28°02'50"N 90°27'19"E|Kangchenjunga||0 (3)|Bhutan/China
...
93|Labuche Kang III/East|7,250|23,786|570|Labuche Himalaya|28°18'05"N 86°23'02"E|Labuche Kang||0 (0)|China
...

It’s all data seperated by a “|”. For this exercise, if the year of the first ascent is empty, I need to replace the “||” with “|unclimbed|”

I can’t do it like this:

%s/||/|unclimbed|/p

Because that would replace other empty fields. So my question is, how do I only replace that specific field?

Advertisement

Answer

The sed s command accepts flags that specify which field to replace. You can use that with something like:

sed '/||[^|]*|[^|]*$/s/|[^|]*/|unclimbed/8'

to do what you want (I make no claims about the robustness of this expression, and fully expect there are edge cases for which it fails).

On the other hand, awk is ideally suited to this, and you can do things like:

awk '$9==""{$9 = "unclimbed"}1' FS=| OFS=| input

Again, these are intended as demonstrative examples only, and I make no claims regarding robustness.

Advertisement