Delete a column from a delimited file in linux

前端 未结 7 1042
星月不相逢
星月不相逢 2020-12-19 02:43

I have a file in the following format:

col1|col2|col3|col4
a|b|c|d
e|f||h
i|j|k|l

I would like to delete col3 (with the delimiter \"|\") fr

7条回答
  •  粉色の甜心
    2020-12-19 03:12

    Here's a possible sed solution:

    sed -i.bak filename -e 's;\(^.*|.*|\).*|\(.*\);\1\2;'
    

    This will work great for your example, and could be adjusted for other examples, but isn't really a general purpose solution.

    Explanation:

    -i.bak Edit the file in place, first making a backup called filename.bak.

    \(^.*|.*|\) From the start of the line, match everything up to and including the second delimiter. The parenthesis group this match (group 1).

    .*| Match everything up to and including the last delimiter.

    \(.*\) Match the rest and group (group 2).

    \1\2 Replace all of the previous matches with the text from group 1 and group 2.

提交回复
热议问题