Tokunbo Hiamang
Tokunbo Hiamang

Reputation: 449

Pass parameter into sed command

I am trying to write a bash script in which the user can pass a regex as a parameter. So for example you run the program this way.

./clean_txt.sh s/.*\(my_choices.*gz\)/\1p

In the program, I am using that parameter this way.

ls /home/user/ | sed -n '$1' > cleaned_file.txt
echo "sed -n '$1'"

In my echo, I see the regular expression passed when when program was initiated. But my cleaned_file.txt is empty. The only way this works is if I hardcode the a regular expression into the program itself but that defeats the purpose of what I am trying to do.

Any idea on how I can pass that parameter into the sed command?

Upvotes: 1

Views: 843

Answers (1)

Tom Fenech
Tom Fenech

Reputation: 74596

The problem is that your variable is not being expanded. You need to wrap it in double quotes (which is what you're doing in the echo already):

ls /home/user/ | sed -n "$1" > cleaned_file.txt

Note that ls is not needed:

files=( /home/user/* )
sed -n "$1" <<<"${files[@]}" > cleaned_file.txt

Would do the same thing. This uses a glob to create an array containing all the filenames, which is used as input to sed.

Upvotes: 2

Related Questions