This is a test version of Biostars. For the public version, visit https://www.biostars.org.
awk gsub question

Hello, guys!

I've used awk in the past for large file manipulation and substitutions.Recently, I've used it to substitute, for ex letter A with a set of characters:

$ awk '{gsub(/A/,"@@@")}1' in.txt >> out.txt

where in.txt contains strings of letters of various length. (AAA, BBB, CCC, ABABAB etc)

How can I use gsub to replace all characters A in my file with @@@, B with ###, C with %%% etc

I am guessing it should be something close to:

$ awk '{gsub(/A|B|C/,"&123")}1' in.txt > out.txt

Many thanks!

awk
cat in.txt  | sed 's/A/@@@/g' | sed 's/B/###/g' | sed 's/C/%%%/g'  > out.txt

and as @ATpoint mentioned:

cat in.txt | awk '{gsub("A","@@@");gsub("B","###");gsub("C","%%%");print}' > out.txt

1 answer

Simplest with tr:

tr "[ABC]" "[@#%]" < your.file > new.file

Or awk:

awk '{gsub("A","@");gsub("B","#");gsub("C","%");print}' your.file > new.file

Log in to answer this question.