# Replace with shell variable in awk

**URL:** <https://community.unix.com/t/replace-with-shell-variable-in-awk/368509>\
**Category:** Shell Programming and Scripting\
**Created:** [September 26, 2017, 12:52pm UTC](https://community.unix.com/t/replace-with-shell-variable-in-awk/368509 "2017-09-26T12:52:20Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ratheesh\_Nair](https://community.unix.com/letter_avatar/ratheesh_nair/32/6_449c533f586939b6e5f246632a46421f.png) [@Ratheesh\_Nair](https://community.unix.com/u/Ratheesh_Nair)\
**Post date:** [September 26, 2017, 12:52pm UTC](https://community.unix.com/t/replace-with-shell-variable-in-awk/368509/1 "2017-09-26T12:52:20Z")

</div>

Hi,

Probably this is a out of scope of the thread. I have a requirement as below

I have a file with below content

```nohighlight
CMD //DS > testfile

```

I have to replace

```nohighlight
//DS

```

with a value which is assigned to a variable outside using awk gsub.  
For example

```nohighlight
var=TEST

```

I expect an output as

```nohighlight
CMD TEST

```

I tried below 2 awk

```nohighlight
awk '{gsub(/\/\/DS/,$var);print}' testfile

```

this fails

```nohighlight
awk '{gsub(/\/\/DS/,"$var");print}' testfile

```

This doesn't replace the var value.

Could you please help me ?

---------- Post updated at 11:52 AM ---------- Previous update was at 11:31 AM ----------

I could accomplish this using sed as below

```nohighlight
sed 's/\/\/DS/,'$var'/g' filename

```

Still looking for awk

Thanks

---

<div class="post-metadata">

**Author:** ![Scrutinizer](https://community.unix.com/user_avatar/community.unix.com/scrutinizer/32/1216_2.png) [@Scrutinizer](https://community.unix.com/u/Scrutinizer)\
**Post date:** [September 26, 2017, 2:20pm UTC](https://community.unix.com/t/replace-with-shell-variable-in-awk/368509/2 "2017-09-26T14:20:39Z")

</div>

Try:

```nohighlight
awk -v var="$var" '{gsub(/\/\/DS/,var);print}' testfile

```

--  
Note: The reason your awk attempt did not work is that the single quotes preventes the shell variables from being expanded..
