Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing string in linux using sed/awk based

i want to replace this

#!/usr/bin/env bash

with this

   #!/bin/bash

i have tried two approaches

Approach 1

original_str="#!/usr/bin/env bash"
replace_str="#!/bin/bash"

sed s~${original_str}~${replace_str}~ filename

Approach 2

line=`grep -n "/usr/bin" filename`
awk NR==${line} {sub("#!/usr/bin/env bash"," #!/bin/bash")}

But both of them are not working.

like image 573
Subham Tripathi Avatar asked Aug 03 '15 07:08

Subham Tripathi


People also ask

How do you use sed command to replace a string in a file?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.

How do I replace a word in awk?

awk has two functions; sub and gsub that we can use to perform substitutions. sub and gsub are mostly identical for the most part, but sub will only replace the first occurrence of a string. On the other hand, gsub will replace all occurrences.

Can I use awk with sed?

Combining the Two. awk and sed are both incredibly powerful when combined. You can do this by using Unix pipes. Those are the "|" bits between commands.


2 Answers

You cannot use ! inside a double quotes in BASH otherwise history expansion will take place.

You can just do:

original_str='/usr/bin/env bash'
replace_str='/bin/bash'

sed "s~$original_str~$replace_str~" file
#!/bin/bash
like image 124
anubhava Avatar answered Oct 29 '22 14:10

anubhava


Using escape characters :

    $ cat z.sh
    #!/usr/bin/env bash

    $ sed -i "s/\/usr\/bin\/env bash/\/bin\/bash/g" z.sh

    $ cat z.sh
    #!/bin/bash
like image 34
Venkatesh Parthasarathy Avatar answered Oct 29 '22 13:10

Venkatesh Parthasarathy