Copying a string from a file using shell script

Hello everyone

I am completely new to shell scripting in linux. I wan to write a script to search for a certain string from a .txt file and copy the string which apears just after tat searched string.

Eg: in a file- try.txt , we have a line saying: "roses are red, so what do i do"

I want ot search for the string "roses" and then copy the next string i.e. "are" and assign it to a variable.

Could anyone help me with this.

Like this since you are in Linux:

$ cat file
roses are red, so what do i do
nothing, just get the next string
$ var=$(grep -oP '(?<=roses )\S+' file)
$ echo $var
are

Guru.

1 Like

Hey!!!

Welcome to the Unix and Linux Forum!!!!

Try someting like this,

First of all, you haven't mentioned, What shell you are using, Here you go with bash.

var=$(sed 's/.*roses \([^ ]*\).*/\1/g' try.txt)
echo $var

Please use code tag for code samples and data samples in future.

Thanks,

Cheers,
Ranga :slight_smile:

1 Like
$ cat temp.sh
var=`awk '{ for (i=1; i<NF; i++) { if ($i ~ /roses/) { i++; print $i; exit }}}' try.txt`
echo $var
$ ./temp.sh
are