I'd like to delete all columns before the label_port
column. Unluckily it's always at a different position. I'm looking for a way to count the characters before label_port
in the first line and then delete this number of chars in each line. Anyone has an idea?
| log_port|local_port|label_port| mtu|
| 0x10100| 1| 7| 9122|
| 0x10500| 5| 8| 9122|
| log_port|local_port|slocal|label_port| mtu|
| 0x10100| 1| 0| 7| 9122|
| 0x10500| 5| 0| 8| 9122|
CodePudding user response:
This might work for you (GNU sed):
sed -E '/\|label_port/h;G;:a;s/^.(.*\n).(.*\|label_port)/\1\2/;ta;s/\n.*//' file
Make a copy of any line that contains |label_port
.
Append the copy to every line.
Using pattern matching, remove characters from the start of each line until the appended line matches the start of its line.
Remove the newline and any artefacts.
CodePudding user response:
$ awk 'NR==1{s=index($0,"|label_port")} {print substr($0,s)}' file
|label_port| mtu|
| 7| 9122|
| 8| 9122|
CodePudding user response:
With awk
:
query='
# first line: find where the "label_port" column starts
(NR==1) { n = match($0, "[|][ ]*label_port[|].*$") }
# all lines: print starting from the "label_port" column
{ print substr($0, n) }
'
or: awk '(NR==1){n=match($0,"[|][ ]*label_port[|].*$")}{print substr($0,n)}' file
1.
awk "$query" <<'EOF'
| log_port|local_port|label_port| mtu|
| 0x10100| 1| 7| 9122|
| 0x10500| 5| 8| 9122|
EOF
|label_port| mtu|
| 7| 9122|
| 8| 9122|
awk "$query" <<'EOF'
| log_port|local_port|slocal|label_port| mtu|
| 0x10100| 1| 0| 7| 9122|
| 0x10500| 5| 0| 8| 9122|
EOF
|label_port| mtu|
| 7| 9122|
| 8| 9122|
remark: I'm not very confident in my awk
skills, there might be a better way to do it.