0

Hi I have wrapped a sed command (which works out it's own) within a shell function.

#!/bin/bash

snp2fasta() { 
sed -i "s/^\(.\{'$2'\}\)./\1'$3'/" $1; 
}

and call it with

$ ./snp2fasta input.txt 45 A

no changes are made to input.txt

However if I simply do

$ sed -i 's/^\(.\{45\}\)./\1A/' input.txt

then this works and the file is changed by changing the 45th character to an A.

However when wrapping into a shell script (to handle command line variables) the shell script snp2fasta.sh runs fine, but no changes are made to the file.

why is this?

5
  • It will be an escaping problem. put set -x just before the sed call to see what it actually runs. Commented Jun 13, 2014 at 8:22
  • i get no output from terminal when using set -x before the sed command Commented Jun 13, 2014 at 8:25
  • sorry @Jayesh - made a mistake - I do actually put the file as argument one and have edited post Commented Jun 13, 2014 at 8:26
  • hi @Jayesh I call ./snp2fasta in the second code block - I call it from the command line. is that what you mean? Commented Jun 13, 2014 at 8:30
  • @brucezepplin ok..look it. The shell doesn't expand variables inside single quotes. Try with expand variable in "".like sed -i 's/^\(.\{"$2"\}\)./\1"$3"/' "$1"; Commented Jun 13, 2014 at 8:43

1 Answer 1

1

if you put it into a script, no more need of the function call ouside the script, use it directly intor the script.

Like on the other related post ( Use argument to...) about state it (to secure thje $1,2 and 3 content)

#!/bin/bash

# argument passed to script (or any other source if needed like intern to script)
File=$1
Place=$2
NewChar=$3

# sed with unambigous variable content
sed -i "s/^\(.\{${Place}\}\)./\1${NewChar}/" ${File}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.