sed using mac and Dollar sign

时间:2018-03-12 18:12:42

标签: bash macos sed

I am running a script and this is part of it:

cat ../my_file.txt | sed -e $'s/\t#.*$/found_pattern/g'

This is quite working. So far, so good. Now I want to use this part as a variable $'s/\t#.*$/found_pattern/g'

When I am trying to run the following it wont work:

THISVAR="$'s/\t#.*$/found_pattern/g'"
cat ../my_file.txt | sed -e ${THISVAR}

I think the dollar sign won't get interpreted. Can you guys help me out?

Thanks and have a great day.

1 个答案:

答案 0 :(得分:3)

当你在引号中加上$时,它成为变量值的一部分,而不是用作解释转义序列的元字符。试试这个:

THISVAR=$'s/\t#.*$/found_pattern/g'
cat ../my_file.txt | sed -e "$THISVAR"

双引号THISVAR来解释变量,但在传递给sed之前阻止shell对其值进行标记。

此外,您不需要cat - 只需将文件名直接传递给sed。

sed -e "$THISVAR" ../my_file.txt
相关问题