-1

I am writing a bash shell script in which I want to use two shell commands sed and egrep.

My bash shall script read a text file q2.txt and then do some actions using egrep and sed.

The code is as given below.

#!/bin/bash
var=$(<q2.txt)

sed "s/^[ \t]*//" -i var
grep -v '^/\*.*\*/$' var
echo "$var"

I read the content of q2.txt in variable var. Then remove the tabs and spaces using sed s/^[ \t]*//" -i var and update my var.

Then execute grep -v '^/\*.*\*/$' var on my updated variable to select some lines with specific start and end.

But in the ouput, It seems like grep and sed are not applicable to var.

Output
sed: can't read var: No such file or directory
grep: var: No such file or directory
Rafael
  • 7,605
  • 13
  • 31
  • 46
Stupid420
  • 1,347
  • 3
  • 19
  • 44
  • `var` is treated as a filename by sed and grep... but there's no reason to try to read a file into a shell variable for this. Have you heard of piping one processes output into another processes input? – Shawn Sep 20 '18 at 03:09
  • Possible duplicate of [shell variable in a grep regex](https://stackoverflow.com/q/18147884/608639), [grep for expression containing variable](https://stackoverflow.com/q/5142729/608639), etc. – jww Sep 20 '18 at 03:52

2 Answers2

1

Here is a much simpler approach

cat q2.txt | sed "s/^[ \t]*//" | grep -v '^/\*.*\*/$'
Rafael
  • 7,605
  • 13
  • 31
  • 46
Leonard
  • 13,269
  • 9
  • 45
  • 72
  • Your grep regular expression isn't equivalent to the OP's. (Though who knows if his was what he actually wants...) – Shawn Sep 20 '18 at 03:12
  • Um - I cut and pasted it. In what way do you think it differs? – Leonard Sep 20 '18 at 03:13
  • Yours didn't escape the asterisks and I think was missing stuff. Looks like it was fixed in an edit though. – Shawn Sep 20 '18 at 03:14
1

The problem is more about shell variables, rather than sed/grep.

See:

Also better to use the Pipe (|) as the other answer has showed, so you don't have to store the intermediate result.

ryenus
  • 15,711
  • 5
  • 56
  • 63