shell script cut from variables

1.5k views Asked by At

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!

2

There are 2 answers

2
Cyrus On BEST ANSWER

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)
0
glenn jackman On

Cyrus has my vote. An awk alternative if GNU grep is not available:

awk -F'&' 'NF==2 && $1 ~ /aaa/ {print $2}' file

Using & as the field separator, for lines with 2 fields (i.e. & must be present) and the first field contains "aaa", print the 2nd field.


The error with your answer is that you are treating the grep output like a filename in the cut command. What you want is this:

grep 'aaa.*&' file | cut -d'&' -f2

The pattern means "aaa appears before an &"