简体   繁体   中英

Replace Nth CSV field where first field match string Bash

I'm trying to replace the content of a csv field based on the first one. I tried something with sed - found in another thread - but I'm unable to obtain a proper result.

Example :

57c5b4da8ef722a0d4b0bbd9727982d2;510;1020;20130410
4858ecf7bf221fd8a3792615d8008dd8;530;4050;20130412

I want to be able to replace field content based on its number and where the first field contain "57c5b4da8ef722a0d4b0bbd9727982d2".

My current sed line work only for the last field :

sed -i 's/\(57c5b4da8ef722a0d4b0bbd9727982d2\)\(;.*;\).*/\1\220130401/' myfile

I think you are trying to replace third and last field(if ; is a delimiter) with the number 20130401 ,

$ sed 's/^\(57c5b4da8ef722a0d4b0bbd9727982d2\)\(;[^;]*;\).*$/\1\220130401/g' file
57c5b4da8ef722a0d4b0bbd9727982d2;510;20130401
4858ecf7bf221fd8a3792615d8008dd8;530;4050;20130412

May this be ok?

awk -F\; '$1=="57c5b4da8ef722a0d4b0bbd9727982d2" {$NF=220130401}1' OFS=\; file
57c5b4da8ef722a0d4b0bbd9727982d2;510;1020;220130401
4858ecf7bf221fd8a3792615d8008dd8;530;4050;20130412

If first field is 57c5b4da8ef722a0d4b0bbd9727982d2 replace last field to 220130401

This might work for you (GNU sed):

sed 's/[^;]*/xxx/2' file

This replaces the second field with xxx .

If you want the second field of a particular line, use:

sed '/57c5b4da8ef722a0d4b0bbd9727982d2/s/[^;]*/2' file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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