user3546860
user3546860

Reputation: 147

awk: how to delete first and last value on entire column

I have a data that is comprised of several columns. On one column I would like to delete two commas that are each located in beginning and the end of entire column. My data looks something like this:

a    ,3,4,3,2,
b    ,3,4,5,1,
c    ,1,5,2,4,5,
d    ,3,6,24,62,3,54,

Can someone teach me how to delete the first and last commas on this data? I would appreciate it.

Upvotes: 2

Views: 158

Answers (3)

Ed Morton
Ed Morton

Reputation: 203229

$ awk '{gsub(/^,|,$/,"",$NF)}1' file
a 3,4,3,2
b 3,4,5,1
c 1,5,2,4,5
d 3,6,24,62,3,54

Upvotes: 4

Mark Setchell
Mark Setchell

Reputation: 207405

You can do it with sed too:

sed -e 's/,//' -e 's/,$//' file

That says "substitue the first comma on the line with nothing" and then "substitute a comma followed by end of line with nothing".

If you want it to write a new file, do this:

sed -e 's/,//' -e 's/,$//' file > newfile.txt

Upvotes: 3

a5hk
a5hk

Reputation: 7834

awk '{sub(/,/,"",$0); print substr($0,0,length($0)-1)}'  input.txt

Output:

a    3,4,3,2,
b    3,4,5,1,
c    1,5,2,4,5,
d    3,6,24,62,3,54

Upvotes: 3

Related Questions