LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   replacing characters in a file with others (https://www.linuxquestions.org/questions/linux-general-1/replacing-characters-in-a-file-with-others-279191/)

pcdude 01-18-2005 03:57 AM

replacing characters in a file with others
 
Hi all.

I would like to know which command to use to sustitute a backslash('\') in a file with a forward slash('/'). Also I want to replace all the semi-colons(';') with colons (':').

I guessing that I'm going to have to use the sed command to do this.

I realize that I should be reading the manual to be getting these answers, I plan on doing this but it may take my quite a while, so I'm asking for something I can use right now.

Thanks in advance.
PCDude

jrtayloriv 01-18-2005 04:45 AM

You were right about the man pages. Sed is one of the most useful tools that you have at your disposal, it would really benefit you to learn as much as you can about it. But I too want a quick answer every now and then so here it is:

Code:

sed 's/\\/\//g'  <INPUT FILE>
Replaces the slashes. Note that you need to use escape characters in front of those slashed to keep from getting sed confused. The g at the end tells it to replace all instances instead of just the first one it finds.

Code:

sed 's/;/:/g' <INPUT FILE>
Ditto, but for the semicolon.

Hope this helps,
jrtayloriv

pcdude 01-18-2005 06:32 AM

Thanks your replies.

That works well. It displays the correct output to the screen but does not make changes to the file.
I know this is typical of Linux and also a good thing.
Code:

sed 's/\\/\//g'  <INPUT FILE>  >  <INPUT FILE>
results in an empty file. I guess you can't read and write a file at the same time.

Is this the next easiest way of doing things:
Code:

sed 's/\\/\//g'  <TEMP FILE>
cat <TEMP FILE> > <INPUT FILE>
rm <TEMP FILE>

Thanks
PCDude

homey 01-18-2005 06:45 AM

Quote:

sed 's/\\/\//g' <INPUT FILE> > <INPUT FILE>
I think maybe sed 's/\\/\//g' file.txt > file1.txt

If you only want one file use a move operation at the end....
mv file1.txt file.txt

jschiwal 01-18-2005 07:01 AM

The option '-i' which stands for inplace will replace the input file immediately.

Also, if you want to replace the '/' character, you can use a different character as a seperator in the command.

sed -i 's#/#\\#g' filename

whansard 01-18-2005 07:12 AM

instead of
sed 's/\\/\//g' <INPUT FILE> > <INPUT FILE>

you can sed 's/\\/\//g' < input file >output file

the input file is the original, and the output file is the changed one.

pcdude 01-19-2005 12:29 AM

Thank you all for your replies.

I think there was some confusion here, I wanted to modify my input file, not output to a different file.
So sed's -i option works well.

Thanks.
PCDude


All times are GMT -5. The time now is 09:00 AM.