onlyf
onlyf

Reputation: 883

Changing the prefix of a file with sed

I would like some advice on this script.
I'm trying to use sed (I didn't manage it with rename) to change a file that contains lines of the format (my test file name is sedtest):

COPY W:\Interfaces\Payments\Tameia\Unprocessed\X151008\E*.*

(that's not the only content of the file).

My goal is to replace the 151008 date part with a different date, I've tried to come up with a solution in sed using this:

sed -i -e "s/Unprocessed\X.*/Unprocessed\X'BLABLA'/" sedtest

but it doesnt seem to work, the line remains unchanged, it's like it doesn't recognize the pattern because of the \. I've tried some alternative delimiters like #, but to no avail.

Thanks in advance for any advice.

Upvotes: 1

Views: 1253

Answers (1)

Tom Fenech
Tom Fenech

Reputation: 74605

There's a couple of issues with your sed command. I would suggest changing it to this:

sed -r 's/(Unprocessed\\X)[0-9]+/\1BLABLA/' file

Since your version of sed supports -i without requiring that you add a suffix to create a backup file, I assume you're using the GNU version, which also supports extended regular expressions with the -r switch. The command captures the part within the () and uses it in the replacement \1. Don't forget that backslashes must be escaped.

If you're going to use -i, I would recommend doing so like -i.bak, so a backup of your file is made to file.bak before it is overwritten.

You haven't shown the exact output you were looking for but I assumed that you wanted the line to become:

COPY W:\Interfaces\Payments\Tameia\Unprocessed\XBLABLA\E*.*

Remember that * is greedy, so .* would match everything up to the end of the line. That's why I changed it to [0-9]+, so that only the digits were replaced, leaving the rest of the line intact.


As you've mentioned using a variable in the replacement, you should use something like this:

sed -r -i.bak "s/(Unprocessed\\X)[0-9]+/\1$var/" file

This assumes that $var is safe to use, i.e. doesn't contain characters that will be interpreted by sed, like \, / or &. See this question for details on handling such cases reliably.

Upvotes: 2

Related Questions