LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   .sh script to replace text (https://www.linuxquestions.org/questions/programming-9/sh-script-to-replace-text-864870/)

zev42 02-24-2011 06:34 PM

.sh script to replace text
 
Hello all,
heres whats up:

i'm trying to script a lil piece to execute in terminal
so when i type something like:

scriptname textfile

the script searches the text file, replaces charecters of my choosing with charecters of my choosing

"sed" im told is the way to go, and i got summat like this going

Code:

#!/bin.sh

bash -c "sed -i.backup -e /s/char/newchar/"

(if need be, i think i can just add another line of "-e /s/char/newchar/" if i need to target more charecters or words as needed.)

the issue with the above code. . . how do i get it to target whatever text file follows the command? without having to manually designate sed to it each time?
e.g. in commanding:

scriptname textfile

how do i get the script to target textfile^^^?

much thanks, and obbvs, im a n00b.

corp769 02-24-2011 06:55 PM

You can use $0 is your script to take place of the first argument.

Code:

#!/bin/bash
sed -i.backup -e /s/char/newchar/ $0


corp769 02-24-2011 06:57 PM

Code:

#!/bin/bash
for var in "$@"
do
    sed -i.backup -e /s/char/newchar/ $var
done

That would process every argument that you give it.

ntubski 02-24-2011 09:15 PM

Quote:

Originally Posted by corp769 (Post 4270303)
You can use $0 is your script to take place of the first argument.

$0 is the scriptname, $1 is the first argument. Also there is an extra slash on the sed command it should be
Code:

sed -i.backup -e s/char/newchar/g
The trailing g is to replace all char with newchar not just the first one on the line.

kurumi 02-26-2011 09:00 AM

Code:

ruby -i.bakup -pne '$_.gsub!(/char/,"newchar");print' file


All times are GMT -5. The time now is 05:24 PM.