Home > Blockchain >  How to change pattern with AWK command in Linux
How to change pattern with AWK command in Linux

Time:08-16

I need your help in awk command, I have a below input file:

sudo su - USER1 -c $Job_dir/abcd.sh abcd pdwd line1

sudo su - USER2 -c $Job_dir/ancd.sh abcd pdwd line2

I want to result like this for all lines (want to add double quotes before $ and at the end of the line :

sudo su - USER1 -c "$Job_dir/abcd.sh abcd pdwd line1"

sudo su - USER2 -c "$Job_dir/ancd.sh abcd pdwd line2"

CodePudding user response:

The awk-file "test.awk" will "add double quotes before $ and at the end of the line".
(In case, the line does not include $, it will just print the line as it is.)

{
   len=length($0);
   pos=-1;
   for(i=0;i<len;i  )
   {
      if(substr($0,i,1)=="$")
      {
         pos=i;
         printf("%s\"%s\"\n",substr($0,1,pos-1),substr($0,pos,len-pos));
      }
   }
   if(pos==-1) print;
}

Run it by

awk -f test.awk textfile.txt > result.txt

The "textfile.txt" is the input file and "result.txt" is the output file.

A shorter version of "test.awk" is with using "index" command to find "$" in the line, see below:

{
   s=index($0,"$")
   if(s!=0)
   printf("%s\"%s\"\n",substr($0,1,s-1),substr($0,s,length($0)-s));
   else
   print;
}
  • Related