0

I have a sql query in a text file and it has a line that looks like:

PARTITION BY (date_key // 100000000);

Now, I want to replace the two forward slashes with the word "DIV".

For that, I did the following in a shell script:

strg=$(grep "PARTITION BY" $entry)    ## $entry has the file_name
strg2=$(echo "$strg" | sed 's%\/\/%DIV%g')

But it did not work as I wanted. On further probing, I got to know that the forward slashes are not even being discovered.

echo "$strg" gives PARTITION BY (date_key ); I also tried

printf ">%s<\n" "$strg" and

printf "%q\n" "$strg"

but the outputs are:

>PARTITION BY (date_key );< and

PARTITION\ BY\ \(date_key\ \)\; respectively.

But when I do grep "PARTITION BY" <file_name> on the command line, I get the correct output:

PARTITION BY (date_key // 100000000); 

Can someone please point out what I am missing?

  • 1
    Why did you escape the slashes in sed 's%\/\/%DIV%g'? Either you use %as separator and you don't need to escape them: sed 's%//%DIV%g' or you do the classical sed 's/\/\//DIV/g' And echo $strg gives the whole line in my bash. – Philippos May 1 '17 at 17:59
  • Your code seems to work for me on MSYS2 using GNU grep 3.0. Perhaps you have a buggy version of grep? – Satya Mishra May 1 '17 at 18:01
  • @Philippos I will take what you said, but the point of concern is is why is "// 100000000" not coming up in the grep. Thanks! – kskp May 1 '17 at 18:04
  • Yes, I understand, but I can't reproduce it. Maybe try without the grepand simply do strg2=$(sed '/PARTITIONED BY/s%//%DIV%' $entry) – Philippos May 1 '17 at 18:07
  • If this is mac with old grep (2.27 i think), it is known that this mac grep is QUITE buggy. – George Vasiliou May 1 '17 at 19:41
2

grep will detect the //:

$ echo 'PARTITION BY (date_key // 100000000);' | grep '//'
PARTITION BY (date_key // 100000000);

sed will replace them:

$ echo 'PARTITION BY (date_key // 100000000);' | sed 's%//%DIV%'
PARTITION BY (date_key DIV 100000000);

To replace // with DIV on every line that matches PARTITION BY:

$ sed '/PARTITION BY/s%//%DIV%' filename

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.