Home > Back-end >  How to use sed to replace a filename in text file
How to use sed to replace a filename in text file

Time:09-15

I have a file: dynamicclaspath.cfg

VENDOR_JAR=/clear-as-1-d/apps/sterling/jar/struts/2_5_18/1_0_0/log4j-core-2.10.0.jar
VENDOR_JAR=/clear-as-1-d/apps/sterling/jar/log4j/2_17_1/log4j-core-2.10.0.jar

I want to replace any occurrence of log4j-core* with log4j-core-2.17.1.jar

I tried this but I know I'm missing a regex:

sed -i '/^log4j-core/ s/[-]* /log4j-core-2.17.1.jar/'

CodePudding user response:

With your shown samples please try following sed program. Using -E option with sed to enable ERE(extended regular expressions) with it. In main program using substitute option to perform substitution. Using sed's capability to use regex and store matched values into temp buffer(capturing groups). Matching till last occurrence of / and then matching log4j-core till jar at last of value. While substituting it with 1st capturing group value(till last occurrence of /) followed by new value of log4j as per OP's requirement.

sed -E 's/(^.*\/)log4j-core-.*\.jar$/\1log4j-core-2.17.1.jar/' Input_file

CodePudding user response:

Using sed

$ sed -E 's/(log4j-core-)[0-9.] /\12.17.1./' input_file
VENDOR_JAR=/clear-as-1-d/apps/sterling/jar/struts/2_5_18/1_0_0/log4j-core-2.17.1.jar
VENDOR_JAR=/clear-as-1-d/apps/sterling/jar/log4j/2_17_1/log4j-core-2.17.1.jar

CodePudding user response:

It depends on possible other contents in your input file how specific the search pattern must be.

sed 's/log4j-core-.*\.jar/log4j-core-2.17.1.jar/' inputfile

or

sed 's/log4j-core-[0-9.]*\.jar/log4j-core-2.17.1.jar/' inputfile

or (if log4j-core*.jar is always the last part of the line)

sed 's/log4j-core.*/log4j-core-2.17.1.jar/' inputfile
  • Related