I have a file with the path of the directory present somewhere in it.I have assigned the path of the directory name to a variable. I want to replace it with another string.The code i used was
sed -e '/$variable/sbcd/' filename.
since the path name includes slashes '/', my sed command is not working. How to solve this out to replace the path name with another string.
As my friend Dileep has correctly pointed out, your question seems to be confusing.
As per my understanding,
"how do i replace $inp1 with $inp2?" means u want to swap the values of the two variables, is it?
If yes then use one more variable and u can easily swap the values stored in the variables.
Replacing a string with a variable means you want to assign a variable to another variable rather then assigning it to some string,rite?
If so den u can do it d same way as u do for string. But here the variable needs to have some value stored in it.
To make it clear, My output file will contain the path of the directory present somewhere in it. I am assigning this path to a variable because the path might keep changing. That is i am using a diff command to check if any additional files are present in any of the two directories i am comparing. The command displays in my output the additional file present in it as
only in a/b/c/d File1.txt.
Where a/b/c/d is the path. I dont want to expose the path in my output file.Instead i need to replace it with the input which i accept from the user.I am adding few more strings to the user input and assigning to another variable. So wherever i find the path in my output file i need to replace it with the modified user input.
assuming my variable are var1 and var2. When i tried
sed -e "s#$var1#$var2#" filename it didnt work.
2nd question
sed -e "s#$variable#sbcd#" filename
This command replaces $variable with the sring sbcd. What if i need to replace sbcd with the variable?
sed -e "s#sbcd#$variable#" filename - is not working.
Based on my understanding,Let us assume the directory user inputs is in the variable $USERIN.Now you want to do filter the output file so as to replace the exact directory path with the one user provides/inputs.
sed -e s#path_to_replace#$USERIN# file.txt
But the above code doesn't modify the file,it just extracts the contents and display it to you.If you want to alter the file please do this :
sed -e s#path_to_replace#$USERIN# file.txt > file1.txt
mv file1.txt file.txt
"The redirection symbol ">" directs the output from sed to the file newfile. Don't redirect the output from the command back to the input file or you will overwrite the input file. This will happen before sed even gets a chance to process the file, effectively destroying your data."