0

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?

6 Answers 6

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

or, 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..
You can't use that if 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.
1

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.

1 Comment

You need to use >> 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.
1
grep -Po '(?<=aaa ")([^"]*)(?=")' FILE_1 >> FILE_2

1 Comment

Nice.. I didn't think about using the negative assertion along with -o, but it seems to work, and is a good way to avoid using a grep | sed pipe..
0

If I understood correctly the question, and so you have a file containing:

word1a "word1b"
word2a "word2b"
word3a "word3b"

You can use sed to extract the value contained between quotes, and then redirect to a file

sed 's/.*"\(.*\)"/\1/' FILE_1 > FILE_2

Comments

0

You could also use this :

grep '^\s*STRING_1\s*\".*\"\s*$' FILE_1 | awk -F \" '{printf $2"\n"}' >> FILE_2

It correctly handles multiple blank characters of the input file, and appends a newline after STRING_2 at the end of FILE_2.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.