简体   繁体   中英

How to replace every word with another word from a file using awk ( the words are given as command line parameters in awk)

I did something like this but nothing is printing


#!/bin/bash

if [ $# -eq 0 ]
then
        echo 'There are no words'
        exit 1
fi
echo | awk 'BEGIN {gsub(/ARGV[1]/,"ARGV[2]");  print}' $@

I think it is because I don't have the file specified but how can I specify it if I already read the words from the command line input in awk

You can do something like this

#!/bin/bash

if [ $# -lt 3 ]
then
        echo "usage: $0 str1 str2 file [file...]"
        exit 1
fi
exec awk 'BEGIN {s=ARGV[1]; r=ARGV[2]; delete ARGV[1]; delete ARGV[2]} {gsub(s,r);  print}' "$@"

if you are using the arguments to awk that are not filenames you have to remove them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM