use commandline arguments in a sed command
I'm not sure that $1
, $2
… and so on can be accessed from command line.
Instead, you could try to run your line from a function. You definitely can pass argument to functions.
foo() { sed 's/^\(.\{'"$2"'\}\)./\1'"$3"'/' "$1"; }foo out2.fa 2 A
Edit: As suggested in comments, I added double-quotes around the argument references to prevent spaces from breaking command parsing (That should not be necessary around $2
as we just pass an integer, but it's much better for $1
and $3
.
Update:
While what I say after the horizontal line (the original answer) is true in general, the real problem is the OP's mistaken belief that positional string arguments ($1
, ...) can be passed to sed
with arguments after the 1st post-script (filename) argument.
All arguments after sed
's script argument are, in fact, filename arguments, and sed
has no concept of other types of arguments or shell variables in general - any references to shell variables or arguments must be expanded BEFORE the script is passed to sed
.
Generally, arguments $1
, ... are shell-only constructs that refer to the arguments passed to either the current shell or, inside a shell function, that function.
- @Qeole's answer provides a solution based on a shell function, which is the best option.
- Alternatively, use variables:
countBefore=2 newChar='A'sed 's/^\(.\{'"$countBefore"'\}\)./\1'"$newChar"'/' out2.fa
Note:
- You say
changes the 2nd position to an A
. Actually, your command effectively replaces the 3rd character ($countBefore+1
-nth).) - You say,
I am currently wrapping the arguments in ''
. Actually, it's thesed
script that's enclosed in''
, and you're splicing in unquoted argument references. My variable-based solution double-quotes the spliced-in variable references for robustness. The alternative to splicing in variable references is to simply double-quote the entire
sed
script and use embedded variable references:sed "s/^\(.\{$countBefore\}\)./\1$newChar/" out2.fa
sed: -e expression #1, char 21: Invalid content of \{\}
is GNU sed
's way of saying that what you specified to go inside {...}
($1
) does not amount to a valid repetition-count expression.
In other words: the value of $1
in your case is NONE of the following:
- a mere decimal number (e.g.,
2
) - a decimal number followed by
,
, optionally followed by another decimal number (e.g.,2,
or2,3
) ,
, followed by a decimal number (e.g.,,3
)
Make sure that $1
is one of the above.