Forward slash not detected in "grep" command

7,276

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
Share:
7,276

Related videos on Youtube

kskp
Author by

kskp

Updated on September 18, 2022

Comments

  • kskp
    kskp almost 2 years

    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?

    • Philippos
      Philippos about 7 years
      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.
    • Satya Mishra
      Satya Mishra about 7 years
      Your code seems to work for me on MSYS2 using GNU grep 3.0. Perhaps you have a buggy version of grep?
    • kskp
      kskp about 7 years
      @Philippos I will take what you said, but the point of concern is is why is "// 100000000" not coming up in the grep. Thanks!
    • Philippos
      Philippos about 7 years
      Yes, I understand, but I can't reproduce it. Maybe try without the grepand simply do strg2=$(sed '/PARTITIONED BY/s%//%DIV%' $entry)
    • George Vasiliou
      George Vasiliou about 7 years
      If this is mac with old grep (2.27 i think), it is known that this mac grep is QUITE buggy.