Home > Net >  sed cutting first match in expression
sed cutting first match in expression

Time:08-26

from the original file I have this

"Reserved DB Instances","State","Start Time"
"alpha-db-dev-26aug2021","active","2021-08-26T06:29:11.121000 00:00"
"beta-db-dev-26aug2021","active","2021-08-26T09:30:49.669000 00:00"
"charlie-db-dev-8dec2021","active","2021-12-08T06:36:26.307000 00:00"

the goal is to remove all of the numbers after T, without eliminating the word "Time"

running the command sed -e s/[0-9]T.*//g csvtest2.csv gives me this output

"Reserved DB Instances","State","Start Time"
"alpha-db-dev-26aug2021","active","2021-08-2
"beta-db-dev-26aug2021","active","2021-08-2
"charlie-db-dev-8dec2021","active","2021-12-0

The problem here is that the last number of the dates gets cut off.

The expcted output should be like this:

"Reserved DB Instances","State","Start Time"
"alpha-db-dev-26aug2021","active","2021-08-26"
"beta-db-dev-26aug2021","active","2021-08-26"
"charlie-db-dev-8dec2021","active","2021-12-08"

I cannot use sed -e s/T.*//g csvtest2.csv as this would result in a format like this despite the date being correct it cut off the word "Time"

"Reserved DB Instances","State","Start 
"alpha-db-dev-26aug2021","active","2021-08-26
"beta-db-dev-26aug2021","active","2021-08-26
"charlie-db-dev-8dec2021","active","2021-12-08

CodePudding user response:

You may use this sed:

sed '2,$ s/T[0-9][^"]*//' file

"Reserved DB Instances","State","Start Time"
"alpha-db-dev-26aug2021","active","2021-08-26"
"beta-db-dev-26aug2021","active","2021-08-26"
"charlie-db-dev-8dec2021","active","2021-12-08"

Breakup:

  • 2,$: Do this from line no. 2 to last line
  • s/T[0-9][^"]*//: Substitute command that matches letter T followed by a digit and everything that is not " thus stopping before last ". This is replaced with just an empty string.

CodePudding user response:

Using sed

$ sed -E 's/T[0-9:. ] //' input_file
"Reserved DB Instances","State","Start Time"
"alpha-db-dev-26aug2021","active","2021-08-26"
"beta-db-dev-26aug2021","active","2021-08-26"
"charlie-db-dev-8dec2021","active","2021-12-08"

CodePudding user response:

Was able to get it after fiddling around and changing my logic using sed -e s/T[0-9].*/\"/g

This produced the expected result

"Reserved DB Instances","State","Start Time"
"alpha-db-dev-26aug2021","active","2021-08-26"
"beta-db-dev-26aug2021","active","2021-08-26"
"charlie-db-dev-8dec2021","active","2021-12-08"

Thank you so much for everyone's input!

  • Related