简体   繁体   English

使用sed或awk替换每行最后一个定界符之后的数据

[英]replace data after last delimiter of every line using sed or awk

I have a text file A.txt , all lines in which have the same number of fields separated by pipe | 我有一个文本文件A.txt ,其中所有行都具有由管道|分隔的相同数量的字段| delimiter. 分隔符。 I need to replace , with | 我需要更换,| for the data after the last delimiter of each line. 每行最后一个定界符之后的数据。

Example: 例:

1,2|3,4|5|6,7,8
1,8|4|6,5,3|4,5

Desired output, (only replace , with | after last delimiter): 所需的输出,(仅替代,|最后一个分隔符后):

1,2|3,4|5|6|7|8
1,8|4|6,5,3|4|5

How to achieve this using sed or awk ? 如何使用sedawk实现此目的?

With awk : awk

awk 'BEGIN{FS=OFS="|"} gsub(",", "|", $NF)'
  • BEGIN{FS=OFS="|"} sets both the input and output field delimiter as literal | BEGIN{FS=OFS="|"}会将输入和输出字段定界符都设置为文字|

  • gsub(",", "|", $NF) substitute all ( gsub() ) , s with | gsub(",", "|", $NF)替代所有( gsub() , S采用| in the last field ( $NF ) 在最后一个字段( $NF

Example: 例:

$ awk 'BEGIN{FS=OFS="|"} gsub(",", "|", $NF)' <<<'1,2|3,4|5|6,7,8'
1,2|3,4|5|6|7|8

$ awk 'BEGIN{FS=OFS="|"} gsub(",", "|", $NF)' <<<'1,8|4|6,5,3|4,5'
1,8|4|6,5,3|4|5
$ cat ip.txt 
1,2|3,4|5|6,7,8
1,8|4|6,5,3|4,5

with sed sed

$ sed -E ':a s/^(.*\|[^,]+),([^|]+)$/\1|\2/g; ta' ip.txt 
1,2|3,4|5|6|7|8
1,8|4|6,5,3|4|5
  • :a and ta to loop sed command until there is a match found :ata循环sed命令,直到找到匹配项
  • ^(.*\\|[^,]+) from start of line to | 从行首到| ^(.*\\|[^,]+) followed by non , characters. 其次是非,字符。 * and + will try to match as much as possible *+会尝试尽可能匹配
  • , match a comma ,用逗号匹配
  • ([^|]+)$ after the comma, there should not be any | ([^|]+)$在逗号后面,不应有任何| character till end of line 字符直到行尾


with perl perl

$ perl -F'\|' -lane '$F[-1] =~ tr/,/|/; print join "|",@F' ip.txt 
1,2|3,4|5|6|7|8
1,8|4|6,5,3|4|5
  • -F'\\|' split input line on | |上分割输入线 and save to @F array 并保存到@F数组
  • $F[-1] =~ tr/,/|/; for last element of array, replace all , with | 对于数组的最后一个元素,|替换all |
  • print join "|",@F print the modified @F array with | print join "|",@F|打印修改后的@F数组 as separator 作为分隔符

And for some regex magic: 对于一些正则表达式魔术:

$ perl -pe 's/.*\|(*SKIP)(*F)|,/|/g' ip.txt
1,2|3,4|5|6|7|8
1,8|4|6,5,3|4|5
  • .*\\|(*SKIP)(*F) skip the pattern until last | .*\\|(*SKIP)(*F)跳过模式直到最后|
  • then replace all , with | 然后全部更换,|

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM