1

I need to insert '--' at the beginning of the line if line contains word VARCHAR(1000)

Sample of my file is:

TRIM(CAST("AP_RQ_MSG_TYPE_ID" AS NVARCHAR(1000))) AP_RQ_MSG_TYPE_ID, TRIM(CAST("AP_RQ_PROCESSING_CD" AS NVARCHAR(1000))) AP_RQ_PROCESSING_CD, TRIM(CAST("AP_RQ_ACQ_INST_ID" AS NVARCHAR(11))) AP_RQ_ACQ_INST_ID, TRIM(CAST("AP_RQ_LOCAL_TXN_TIME" AS NVARCHAR(10))) AP_RQ_LOCAL_TXN_TIME, TRIM(CAST("AP_RQ_LOCAL_TXN_DATE" AS NVARCHAR(10))) AP_RQ_LOCAL_TXN_DATE, TRIM(CAST("AP_RQ_RETAILER" AS NVARCHAR(11))) AP_RQ_RETAILER,

I used this command

sed 's/\(^.*VARCHAR\(1000\).*$\)/--\1/I' *.sql

But the result is not as expected. Does anyone have idea what am I doing wrong?

Dinesh Subedi
  • 2,603
  • 1
  • 26
  • 36

3 Answers3

4

this should do:

sed 's/.*VARCHAR(1000).*/--&/' file

The problem in your sed command is at the regex part. By default sed uses BRE, which means, the ( and ) (wrapping the 1000) are just literal brackets, you should not escape them, or you gave them special meaning: regex grouping.

The first and last (..) you have escaped, there you did right, if you want to reference it later by \1. so your problem is escape or not escape. :)

Kent
  • 189,393
  • 32
  • 233
  • 301
0

Use the following sed command:

sed '/VARCHAR(1000)/ s/.*/--\0/' *.sql

The s command appplies to all lines containing VARCHAR(1000). It then replaces the whole line .* by itself \0 with -- in front.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • awk way `awk '/VARCHAR(1000)/ {print "--"$0}' *.sql` –  Jun 10 '14 at 08:44
  • While it will work with awk too, I don't think this is an awk task. It's a typical task one would manually do in a text editor, and for those is sed. That's how I decide between using sed or awk. – hek2mgl Jun 10 '14 at 08:45
  • I was showing a similar(practically identical) way in awk. Not necessarily saying it is better. Just thought id provide more information and let them choose which they like :) I personally prefer to use awk over sed as i find it more readable. –  Jun 10 '14 at 08:48
  • @Jidder your awk command won't work. since you have to escape the `( and )`, something like `awk '$1=/VARCHAR\(1000\)/?"--"$1:$1' file` . and I am with hek2mgl, this is not an awk task, even tough awk can do it too. – Kent Jun 10 '14 at 08:53
  • I understand the backslashes, but why have you added all the `$1`'s and `/?` .It works fine with the backslashes but otherwise exactly the same ? Also i was just providing an alternative which is why i didnt post it as a real answer :) –  Jun 10 '14 at 08:56
0

Through awk,

awk '/VARCHAR\(1000\)/ {sub (/^/,"--")}1' infile > outfile
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274