0

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!

Jacky
  • 3
  • 3

1 Answers1

3

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
user122992
  • 150
  • 1
  • 8
  • Thanks very much for the response! I tried both methods. No go. Here is what I see :
    [root@localhost ~]# x=$(grep "^/dev/disk/by-id/scsi-" /tmp/del.txt | sed {'s/=.//'})
    [root@localhost ~]# $x -bash: /dev/disk/by-id/scsi-3644a8420420897001f2af8cc054d33bb: Permission denied
    [root@localhost ~]# x=$(grep "^/dev/disk/by-id/scsi-*" /tmp/del.txt | sed {'s/=.*//'})
    [root@localhost ~]# $x -bash: /dev/disk/by-id/scsi-3644a8420420897001f2af8cc054d33bb: Permission denied
    – Jacky May 24 '17 at 06:17
  • Sorry for the messy log snip. it is giving this error -- `-bash: /dev/disk/by-id/scsi-3644a8420420897001f2af8cc054d33bb: Permission denied` or `-bash: /dev/disk/by-id/scsi-3644a8420420897001f2af8cc054d33bb,1171becbace78: No such file or directory` – Jacky May 24 '17 at 06:24
  • @Jes it looks like you are trying to execute `$x`. Don't do that; it's data, not a command. If you want to see what `$x` contains, use `echo "$x"`. – Gordon Davisson May 24 '17 at 07:16