Search code examples
bashshellshellcode

shell script cut from variables


The file is like this

aaa&123
bbb&234
ccc&345
aaa&456
aaa$567
bbb&678

I want to output:(contain "aaa" and text after &)

123
456

I want to do in in shell script, Follow code be consider

#!/bin/bash
raw=$(grep 'aaa' 1.txt)
var=$(cut -f2 -d"&" "$raw")
echo $var

It give me a error like

cut: aaa&123
aaa&456
aaa$567: No such file or directory

How to fix it? and how to cut (or grep or other) from exist variables?

Many thanks!


Solution

  • With GNU grep:

    grep -oP 'aaa&\K.*' file
    

    Output:

    123
    456
    

    \K: ignore everything before pattern matching and ignore pattern itself

    From man grep:

    -o, --only-matching
          Print only the matched (non-empty) parts of a matching line,
          with each such part on a separate output line.
    
    -P, --perl-regexp
          Interpret PATTERN as a Perl compatible regular expression (PCRE)