-1

I'm trying to print the values of the lines associated with dates, now I will be giving an alternate code that pretty much covers what I mean

My File Contents Are:

2020-10-9 Sold 50 Shirts
2021-09-4

My Script is:

export x=10
sed -n '/2020-"$x"/p' < filename 

I know I could use 10, but that's not my point here I'm trying to figure out how to use sed using an argument thats an integer.

Desired output would be

2020-10-9
romainl
  • 172,579
  • 20
  • 259
  • 291
  • 2
    `sed` *won't* read variables from the environment. What you need to do is have the shell build the `sed` script dynamically from shell variables. Whether those variables are exported or not is irrelevant. – chepner Nov 03 '21 at 19:46
  • 1
    I wouldn't use `sed` for this at all. Use `awk` instead, which *can* take arguments. `awk -v d="$x" '$0 ~ "2020-"d'`. – chepner Nov 03 '21 at 19:48
  • 2
    See: [Difference between single and double quotes in bash](http://stackoverflow.com/q/6697753/3776858) – Cyrus Nov 03 '21 at 19:51

3 Answers3

0

Bash dosn't interpolate variables in single quotes

Your example with double quotas works well

$ cat 1.txt 
2020-10-9 Sold 50 Shirts
2021-09-4
$ export x=10
$ sed -n "/2020-$x/p" < 1.txt 
2020-10-9 Sold 50 Shirts
Dmitry T.
  • 91
  • 2
0

You can use another approach, for example with cat and grep:

x=10
cat 1.txt | grep 2020-$x

Or, as chepner mentioned in comment, just:

x=10
grep 2020-$x 1.txt
tarkh
  • 1,843
  • 1
  • 7
  • 10
  • 3
    You don't need `cat` at all. `grep "2020-$x" 1.txt` does the same thing. – chepner Nov 03 '21 at 20:09
  • @chepner hypothetically if one were to just grep "-$x" how would you stop bash from interpreting it as an option for grep – BaleKaneSon Nov 03 '21 at 20:46
  • That's what the `-e` option is for. The follow argument is *always* the pattern to use, not another possible option. `grep -e -"$x"` ...` `bash` itself has nothing to do with identifying options. It just passes arguments to `grep`, which interprets its arguments as options or not according to its internal rules. – chepner Nov 03 '21 at 20:48
0

Using sed

$ export x=10
$ sed  -n "s/\(2020-$x-[0-9]\{0,\}\).*/\1/p" input_file
2020-10-9
HatLess
  • 5,048
  • 4
  • 8
  • 28