brucezepplin
brucezepplin

Reputation: 9752

calling and changing a file using sed command within a function

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?

Upvotes: 0

Views: 934

Answers (1)

NeronLeVelu
NeronLeVelu

Reputation: 10039

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}

Upvotes: 1

Related Questions