LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Would you recommend sed to ..... (https://www.linuxquestions.org/questions/linux-newbie-8/would-you-recommend-sed-to-844106/)

ieatbunnies 11-13-2010 05:11 PM

Would you recommend sed to .....
 
I have a document.
I want to replace all the c's and C's in it with %1
all the f's and F's in it with %2

i can get sed to do one of them but for some reason i can't get the script to do all the conversions at once.

Dark_Helmet 11-13-2010 05:15 PM

Have you tried:
Code:

sed -e <pattern1> -e <pattern2> -e . . .

aluser 11-13-2010 05:15 PM

My bet is that you're missing a "g" at the end of your substitution commands. e.g.
Code:

$ echo 'abcdefghABCDEFGH' | sed 's/[fF]/%2/g
> s/[cC]/%1/g'
ab%1de%2ghAB%1DE%2GH

Without 'g', s/// only replaces the first instance of the search pattern that it finds in each line.

edit: oops, I missed Dark Helmet's post. He's right, maybe the problem is confusion about how to do multiple sed commands at once. The multiple -e options is a cleaner way to do it than the literal newline that I used.

ieatbunnies 11-13-2010 07:09 PM

Code:

#!/bin/bash
#
#
for fl in *.txt; do
mv $fl $fl.old
sed -e 's/d/%2/' -e 's/a/%1/' -e 's/e/%3/' $fl.old > $fl
done

cause i want to do all the txt files in that directory and make a backup.
but that seemed to do the trick the -e option. i want to be able to select the file i want to do this too so more reading for me .;'


thanks peeps.

crts 11-14-2010 05:06 AM

Quote:

Originally Posted by ieatbunnies (Post 4157990)
Code:

#!/bin/bash
#
#
for fl in *.txt; do
mv $fl $fl.old
sed -e 's/d/%2/' -e 's/a/%1/' -e 's/e/%3/' $fl.old > $fl
done

cause i want to do all the txt files in that directory and make a backup.
but that seemed to do the trick the -e option. i want to be able to select the file i want to do this too so more reading for me .;'


thanks peeps.

Hi,

You do not need a loop. sed can do this:
Code:

sed -i.old 's/[cC]/%1/g;s/[fF]/%2/g' *.txt
[EDIT]
Just read that you want to select the file, so you do need a loop for your purpose. But you do not need to manually make a backup first. The -i option in sed will create a backup of the file if you give it an extension, e.g. -i.old will create a backup file with extension '*.old ' and before editing the file.


All times are GMT -5. The time now is 04:13 AM.