0
votes

I am using echo and sed to print a string between two strings, but it is giving me error "no such file of directory"

$SEARCH_1=12  
$FO_FILE=myfile.txt

SEARCH=$(head -$SEARCH_1 $FO_FILE | tail -1 | grep BShare)  
LOC=echo $SEARCH_2 | sed 's/\(.*\)BShare>\(.*\)<\/BShare\(.*\)/\2/g'

If I don't use LOC= and use only echo it prints the string correctly. example

<test>mystring</test> will be printed as mystring  

but if I assign the echo command to a variable it says "no such file or directory"

1
what is SEARCH_2? no value is assigned to it, how can it give correct result? - Nachiket Kate
Don't use the dollar sign when you assign a variable: search_1=12; fo_file=myfile.txt. I strongly recommend you don't use ALL_CAPS_VARNAMES, save those for the shell's use -- one day you'll write PATH=5 and wonder why your script is broken. - glenn jackman
Why do you think there is a difference between the assignment to SEARCH (where you use $(...)) and to LOC (where you do not)? - chepner

1 Answers

2
votes

To capture the output of a command and assign it to a variable you need to use backticks or $( ... ), e.g.

LOC=`echo $SEARCH_2 | sed 's/\(.*\)BShare>\(.*\)<\/BShare\(.*\)/\2/g'`

or

LOC=$(echo $SEARCH_2 | sed 's/\(.*\)BShare>\(.*\)<\/BShare\(.*\)/\2/g')

The problem with the original command

LOC=echo $SEARCH_2 | sed 's/\(.*\)BShare>\(.*\)<\/BShare\(.*\)/\2/g'

is that the shell here tries to run what ever $SEARCH_2 evaluates to (with a environmental variable LOC set to value echo), and pipe the output of that to sed.