0

I am trying to use a regular expression to find and replace the contents that are enclosed by two double quotes in a xml file using sed, e.g., "contents like this...".

In particular, I would like to replace whatever the content of autoLogoffTime is with a fixed string "2:15,AM" in the xml file.

Some contents of my XML file

<SystemSettings executionSummaryExportDir="/home/Jts/" autoLogoffTime="11:45,PM" repetitiveSnapshotDelay="500" snapshotCostReminderLimit="10" snapshotExcessiveUsageLimit="50" autoExportDirectory="/home/$

There are a few of these XML files in different directories that I would like to replace the string. The content of autoLogoffTime can be with or without a space in it, e.g.:

autoLogoffTime="11:45,PM" 
autoLogoffTime="11:45, PM"

I tried to find all the characters (white space and non-whitespace) by using * but it does not seem the right regular expression.

sed -i.bak 's/autoLogoffTime="*"/autoLogoffTime="2:15,AM"/g' file.xml

could someone kindly help?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
afp_2008
  • 1,940
  • 1
  • 19
  • 46

1 Answers1

1

First, the best way to modify an XML file is to use XML-specific tools. sed should be used only if those tools are not available. So, use this answer only if there is a good reason why they can't be installed on your system.

In a shell glob, "*" means two double-quotes with any characters between them. sed, however, doesn't use globs, it uses regular expressions. In a regular expression, * means zero-or-more of the previous character. Thus, "*" matches zero-or-more " followed by ".

Try:

sed -i.bak 's/autoLogoffTime="[^"]*"/autoLogoffTime="2:15,AM"/g' file.xml

"[^"]*" matches ", followed by zero-or-more of any character except ", followed by ".

John1024
  • 109,961
  • 14
  • 137
  • 171
  • Thank you, John for the answer. What would you recommend using for XML string replacement? Do you mind providing an answer using a XML-specific tool? Would really appreciate it. – afp_2008 Aug 14 '20 at 23:44
  • 1
    `xmlstarlet` seems to be popular. There may be others. (I've had little reason to use one myself.) – John1024 Aug 14 '20 at 23:49