I'm new to bash scripting, but I want to do the following:
I want to detect the pattern STRING_1 "STRING_2" in FILE_1 and append STRING_2 to FILE_2
what's a concise way to do this?
Your question is fairly vague; but my guess at what you wanted
if STRING_1 exists in FILE_1, append STRING_2 to FILE_2
answer=`grep -c STRING_1 FILE_1`
if [ "$answer" -gt 0 ]
then
echo "$STRING_2" >> FILE_2
fi
grep -c STRING_1 FILE_1 && echo "$STRING_2" >> FILE_2 :) but I'm not sure it is what he meant, although the question is very vague..STRING_2 is not known. An alternative to redShadow's suggestion, but still using if would be: if grep -sq STRING_1 FILE_1; then. No variable, brackets or comparison needed.You could do something like:
sed 's/STRING_1 \"(.*)\"/\1/g' FILE_1 >FILE_2
What's happening here, is sed is searing for everything between the first and second '/' from FILE_1 and sending what's between the second and third '/' to FILE_2.
() groups are assigned to \1, \2, etc... so everything in between the \"s are your STRING_2.
>> to append. It's not necessary to escape the double quotes, but it is to escape the parentheses (unless you use the -r option to sed. It would probably be better to change the pattern from .* to [^"]* since sed regexes are greedy.grep -Po '(?<=aaa ")([^"]*)(?=")' FILE_1 >> FILE_2
-o, but it seems to work, and is a good way to avoid using a grep | sed pipe..This is what I have right now:
sed 's/STRING_1\s*:\s*"([^"]*)"/\1/g' "FILE_1" >> FILE_2;
I want it to detect the following pattern in file 1:
STRING_1 : "STRING_2"
and save STRING_2 to file 2
but this doesn't work, it appends a lot of random stuff to FILE_2(that are not supposed to match)