Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use commandline arguments in a sed command

I want to use commandline arguments in a sed command, where I am currently wrapping the arguments in ''. My command is:

mycomputer$ sed 's/^\(.\{'$1'\}\)./\1'$2'/' out2.fa 2 A

which essentially looks at a line in a file, and changes the 2nd position to an A. This works when I hardcode it in, but the above results in:

sed: -e expression #1, char 21: Invalid content of \{\}

also should I be using $2 and $3 as the commandline arguments given that the filename is technically the first argument?

like image 303
brucezepplin Avatar asked Feb 12 '23 18:02

brucezepplin


1 Answers

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.

like image 61
Qeole Avatar answered Feb 20 '23 07:02

Qeole