sedbasename

Using Sed to Parse Base Filename into Replacement Argument


Working within a directory of two thousand plus of text files, I need to replace a certain string in each of those text files from "template.cmp" into "actualfilename". For example, for a file like mdgen.cmp, I need the original string of "template.cmp" to be changed to "mdgen".

I have tried the following command to no avail:

sed -i 's/template.cmp/$(basename)' ./*

Any idea how I can get around this?


Solution

  • Inside single quotes, $(basename) is just a static string. If you want to run the command basename, you need double quotes, and you need to pass it an argument, or two arguments if you want to trim the extension. Guessing a bit what you are actually trying to do, something like

    for file in *; do
        sed -i "s/template\.cmp/$(basename "$file" .cmp)/" "$file"
    done
    

    Notice also how the dot in the regex should properly be escaped with a backslash or by putting it in a character class [.]; an unescaped . matches any character at all.