Bash – Trying to do grep and sed from a file and push the output into a variable

bashgrepsedshell

Can we do grep and sed from a file and push the output into a variable

grep "^/dev/disk/by-id/scsi-*" /tmp/disks.txt | sed '{'s/=.*//'}'

Output would be like this:

/dev/disk/by-id/scsi-3644a8420420897001f2af8cc054d33bb
/dev/disk/by-id/scsi-3644a8420420897001ef50fcb0f778b86-part3
/dev/disk/by-id/scsi-3644a8420420897001ef50fcb0f778b86-part2

Error:

[/~]# grep "^/dev/disk/by-id/scsi-*" /tmp/disks.txt | sed {'s/=.*//'} >> $x
-bash: $x: ambiguous redirect

Can we push all 3 lines into a variable and call them with foreach?
Thanks!

Best Answer

I have tested, and both the below work in bash shell:

x=`grep "^/dev/disk/by-id/scsi-*" /tmp/disks.txt | sed {'s/=.*//'}`
x=$(grep "^/dev/disk/by-id/scsi-*" /tmp/disks.txt | sed {'s/=.*//'})

Notice first line is backticks, not single quotes.

The >> character in your question sends output to files, not variables.

To answer second part, yes, using output from above, a for loop works:

for line in $x 
do
  echo $line
done