Tremors
Tremors

Reputation: 133

Shell script for replacing characters?

I'm trying to write a shell script that takes in a file(ex. file_1_2.txt) and replaces any "_" with "."(ex. file.1.2.txt). This is what I have but its giving me a blank output when I run it.

read $var
x= `echo $var | sed 's/\./_/g'`
echo $x

I'm trying to store the changed filename in the variable "x" and then output x to the console.

I am calling this script by writing

./script2.sh < file_1_2.txt

Upvotes: 0

Views: 66

Answers (3)

Andreas Louv
Andreas Louv

Reputation: 47099

Threre is not need for sed as bash supports variable replacement:

$ cat ./script2
#!/bin/bash
ofile=$1
nfile=${ofile//_/./}
echo mv "$ofile" "$nfile"
$ ./script2 file_1_2.txt
mv "file_1_2.txt" "file.1.2.txt"

Then just remove echo if you are satisfied with the result.

Upvotes: 0

Qeole
Qeole

Reputation: 9114

Another solution, with bash only:

$ x=file_1_2.txt; echo "${x//_/.}"
file.1.2.txt

(See “Parameter expansion” section in bash manual page for details)

And you can also do this with rename:

$ touch file_1_2.txt
$ ls file*
file_1_2.txt
$ rename 'y/_/\./' file_1_2.txt
$ ls file*
file.1.2.txt

Upvotes: 1

CDe
CDe

Reputation: 181

There is two problems. First, your code has some bugs:

read var
x=`echo $var | sed 's/_/\./g'`
echo $x

will work. You had an extra $ in read var, a space too much (as mentioned before) and you mixed up the replacement pattern in sed (it was doing the reverse of what you wanted).

Also if you want to replace the _ by . in the filename you should do

echo "file_1_2.txt" | ./script2.sh

If you use < this will read the content of `file_1_2.txt" into your script.

Upvotes: 1

Related Questions