I have to remove .. character from a file in Bash script. Example:
I have some string like:
some/../path/to/file
some/ab/path/to/file
And after replace, it should look like
some/path/to/file
some/ab/path/to/file
I have used below code
DUMMY_STRING=/../
TEMP_FILE=./temp.txt
sed s%${DUMMY_STRING}%/%g ${SRC_FILE} > ${TEMP_FILE}
cp ${TEMP_FILE} ${SRC_FILE}
It is replacing the /../ in line 1; but it is also removing the line /ab/ from second line. This is not desired. I understand it is considering /../ as some regex and /ab/ matches this regex. But I want only those /../ to be replaced.
Please provide some help.
Thanks,
NN
The
.is a metacharacter insedmeaning ‘any character’. To suppress its special meaning, escape it with a backslash:Note that you are referring to different files after you eliminate the
/../like that. To refer to the same name as before (in the absence of symlinks, which complicate things), you would need to remove the directory component before the/../. Thus:refer to the same file, assuming
someis a directory and not a symlink somewhere else, but in general,some/path/to/fileis a different file (though symlinks could be used to confound that assertion).Note the careful use of double quotes around the variable
"$x"in theechocommands. I could have used either single or double quotes in the assignment and would have gotten the same result.Test on Mac OS X 10.7.4 with the standard
sed(and shell is/bin/sh, akabash3.2.x), but the results would be the same on any system.