[英]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
? 如何使用
sed
或awk
实现此目的?
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 :a
和ta
循环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)
跳过模式直到最后|
,
with |
,
用|
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.