-2

I have to search string in in file searchstring is Ev_SQL_DIR=/dev/mirror/sched/sql and to be searched in file having content as per below

cat file.txt
Ev_SQL_DIR=/dev/mirror/sched/sql
Ev_TRIG_DIR=/hubdev/mirror/sched/trig
Ev_DB2_ENC_STR={iisenc}lasdbDxMsMFVOJBK0Gsg==
EV_COMPILEOPT=-c -O -fPIC -Wno-deprecated -m64 -mtune=generic -mcmodel=small

I used sed -n '/$searchstring/p' file.txt but it gives below error and I tried to escape also tried to use regex but not able to get it right. any inputs?

sed: -e expression #1, char 24: unknown command: `S'
jww
  • 97,681
  • 90
  • 411
  • 885

1 Answers1

0

You should use double quotes ". Otherwise Bash will not replace the variable $searchstring for its content. Also, try to use it as:

$ searchstring="Ev_SQL_DIR=/dev/mirror/sched/sql"
$ sed -n "/${searchstring//\//\\/}/p" file.txt
Ev_SQL_DIR=/dev/mirror/sched/sql

It seems that you must use the /. Using # doesn't work for me as well :s

An alternative to this is to use grep. I think it's better in this case, because you do not have to worry about the slashes.

$ grep "$searchstring" file.txt 
Ev_SQL_DIR=/dev/mirror/sched/sql

I usually only use sed when I want to replace something, and grep when I want to retrieve a part of a file or string. Grep also has a regex option (-E).

Bayou
  • 3,293
  • 1
  • 9
  • 22
  • Getting a blank value after trying sh-4.1$ echo $searchstring Ev_SQL_DIR=/dev/mirror/sched/sql -sh-4.1$ var=`sed -n "#$searchstring#p" file.txt` -sh-4.1$ echo $var – Sumedh Patil Sep 20 '19 at 09:48
  • @Bayou `#` denotes a comment in `sed` commands, which is why it didn't work. I often use `@` as an alternative delimiter, but it's best to pick a character that is guaranteed not to appear in the delimited pattern (here you'd want a character that isn't a valid character for a linux filename) – Aaron Sep 20 '19 at 10:00
  • @Bayou - as per your suggestion I used `grep` instead of `sed` and it worked and I'm not going to get multiple results as per my comment. Multiple results were going to occur for different requirement and I was able to handle it using `sed`. Thanks – Sumedh Patil Sep 20 '19 at 10:24
  • @Aaron I didn't know that, thanks. I often use use `s#/path/to/dir/#/something/else#`. I guess that it's only a comment when the text starts with `#`. @SumedhPatil you're welcome, I've just learned something myself :-) – Bayou Sep 20 '19 at 10:31
  • 1
    Actually my comment was somewhat incorrect/irrelevant, I'm sorry. Alternative delimiters can be used for `s` (and that includes `#` as you mentionned), but not for `/test/` where you're stuck to escaping slashes.Trying to replace the slashes by `#` would have indeed made it a comment though, suppressing any error. Edit: just checked `man sed` and there's an alternate format for `GNU sed` at least: `\XpatternX`, where any character can be used instead of X – Aaron Sep 20 '19 at 12:16