FGirardi
FGirardi

Reputation: 3

Linux - Replace column value

I have a huge file with many lines and columns. This file is using |~| as column separator.

I would like to replace the value .000000 on the 17 Column for nothing (in this case, erase this value in this specific column).

I tried use sed, but it is replacing the value in all columns. I don't know how specify the column 17.

sed -i 's/.000000//g' filename.txt

How the file is:

20201101 10:24:52.000000|~||~||~|SYSTEM|~||~||~||~|00001|~||~|000326|~||~||~||~||~||~|20201101 10:24:51.000140|~|**20201101 10:24:51.000000**|~|20201101 10:24:52.000912|~|

How I'm expecting the command result:

20201101 10:24:52.000000|~||~||~|SYSTEM|~||~||~||~|00001|~||~|000326|~||~||~||~||~||~|20201101 10:24:51.000140|~|**20201101 10:24:51**|~|20201101 10:24:52.000912|~|

Note: the column I want to change the value, have a different Date and Time for each line. So I just need to specify the column and the value I want to replace, not entire value on the column.

Need to delete last 7 characters on specific column on all lines that the file have value .000000

Thanks.

Upvotes: 0

Views: 386

Answers (4)

FGirardi
FGirardi

Reputation: 3

awk command, worked fine, but in my case, there is some lines that I don't need to remove because don't have this extra characters (milliseconds), so this command will work to export the data to another new file.

$ awk 'BEGIN{FS="\\|~\\|";OFS="|~|"}{sub(/\.000000/,"",$17)}1' file

sed command worked perfect. It replaced all records I don't want in my file just for the column I need.

sed 's/^\(\([^|]*|~|\)\{16\}[^|]*\)\.000000\([^|]*|~|\)/\1\3/' file

Thank you all.

Upvotes: 0

potong
potong

Reputation: 58578

This might work for you (GNU sed):

sed 's/^\(\([^|]*|~|\)\{16\}[^|]*\)\.000000\([^|]*|~|\)/\1\3/' file

Match 16 fields and the first part of the 17th field, followed by .000000 and the last part of the 17th field followed by |~| and replace it by 16 fields and the first part of the 17th field followed by the last part of the 17th field and|~|.

Upvotes: 1

James Brown
James Brown

Reputation: 37464

In awk:

$ awk 'BEGIN{FS="\\|~\\|";OFS="|~|"}{sub(/\.000000/,"",$17)}1' file

Partial output:

...|~|**20201101 10:24:51**|~|...

Pretty-printed:

$ awk '
BEGIN {
    FS="\\|~\\|"                  # or "[|]~[|]"
    OFS="|~|"
}
{
    sub(/\.000000/,"",$17)        # due to the *s in sample data, else /.{7}$/
}1' file                          # output

sub($17,1,17) instead of sub() would work, too.

Upvotes: 3

souser
souser

Reputation: 6128

Is this what you are looking for ?

awk -F '\\|~\\|'  '{print $17}' file | sed -e 's/.000000//'

Upvotes: 0

Related Questions