0

I do have a small requirement of a bash script which will copy part of the line from a file and then append it to another file with some extra text (which contains another variable).

Example

File1.txt content

Warning: pasting the following URL into your browser exposes the OTP secret to Google:
https://www.google.com/chartxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Your new secret key is: xxxxxxxxxxxxxxxxxxxxxx
Your verification code is xxxxxx
Your emergency scratch codes are:
  xxxxxxxx
  xxxxxxxx
  xxxxxxxx
  xxxxxxxx
  xxxxxxxx

So I need to copy only the secret code and then paste it to another file

File2.txt

secret code of user xxxxxxxxxxx is saved

I'm new to Linux as well as scripting so any help on this would be greatly appreciated.

Also, please let me know if my query is not clear.

4
  • Hi, Thanks for the reply I have already added dummy contents of File1 and File2 also removed the variables scenario from this question as this can be considered as irrelevant to what I'm stuck now.
    – Arjun P
    Apr 10, 2020 at 15:47
  • Is "This is your code:" the exact text that your files1 has before the secret code? Apr 10, 2020 at 15:51
  • Not exactly, let me update the code with the exact text in question. It's actually a google-authenticator secret key which I would like to extract and save it to another file
    – Arjun P
    Apr 10, 2020 at 15:57
  • I Have updated the question with actual text,
    – Arjun P
    Apr 10, 2020 at 16:01

1 Answer 1

1

Try this sed:

sed -n 's|Your new secret key is: \(.*\)|secret code of user \1 is saved|p' File1.txt >> File2.txt

It appends the secret code in File1.txt to File2.txt. The secret code is what .* matches and is reproduced by \1.

1
  • Thank you, This was what it intended. I slightly edited your code so that it would accept variables also and now it is working code attached here in case someone wants to know also please let me know my approach with variables is correct? sed -n 's|Your new secret key is: (.*)|user with id '"${user_id}"' has secret \1and pin '"$pin"'|p' file1.txt >> file2.txt
    – Arjun P
    Apr 10, 2020 at 16:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .