2

I have a requirement to search for a variable "nt" ( contains a slash). From a file text1 and remove all lines containing it

$ echo $nt
/u01/app/us1fa01_0/

$ cat text1
/u01/app/fa01/
/u01/app/us1fa01_0/
/u01/app/us1fa01_ps6/

Expected output-

$ cat text1
/u01/app/fa01/
/u01/app/us1fa01_ps6/

I tried the following commands:

  1. sed "/$nt/d" text1

    sed: -e expression #1, char 3: unknown command: `u'
    
  2. sed "|$nt|d" text1

    sed: -e expression #1, char 1: unknown command: `|'
    
  3. sed '\|"$nt"|d' text1

    /u01/app/fa01/
    /u01/app/us1fa01_0/
    /u01/app/us1fa01_ps6/
    

None of the above codes seem to work. Looking for a way out

  • Just edited the value of -nt. It should be $echo $nt /u01/app/us1fa01_0/ – neha dhawan Aug 31 '17 at 12:24
  • In the last version (3), the single quotation marks will inhibit parameter expansion for $nt. So you will search for $nt there, not for its expansion. – King Thrushbeard Aug 31 '17 at 12:32
  • are you not missing the s in sed: sed "s/$nt/d" text1? – joH1 Aug 31 '17 at 12:36
  • No luck $sed "s/$nt/d" text1 sed: -e expression #1, char 8: unknown option to `s' – neha dhawan Aug 31 '17 at 12:40
2

With grep:

grep -Fv -f <(echo "$nt") text1
  • -F - interpret the pattern as a list of fixed strings

  • -v - invert the sense of matching, to select non-matching lines

  • -f - obtain patterns from file, one per line

The output:

/u01/app/fa01/
/u01/app/us1fa01_ps6/
0

With GNU sed (not sure about other sed implementations), you can use \%pattern%, where % is an arbitrary character.

So the following should work:

sed "\%$nt%d" text1
  • That made sense too. Tks – neha dhawan Aug 31 '17 at 12:45
0
$ sed "\#$nt#d" text1 
/u01/app/fa01/
/u01/app/us1fa01_ps6/

sed allows you to use an arbitrary pattern delimiter if you quote it with \.

This will fail if $nt contains any # characters. In this case, use another delimiter.

Note that this will delete line that contains the pattern anywhere on the line.

To force the pattern to match across the whole line, use

$ sed "\#^$nt\$#d" text1

Here, we need to quote the end-of-line anchor $ from the shell with \$.

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.