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.

  • Welcome, Arjun! Add some placeholder text to the files that don't have a single line to indicate so. It is also necessary that you show us your bash script if your variables should be considered. – Quasímodo Apr 10 at 15:38
  • 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 at 15:47
  • Is "This is your code:" the exact text that your files1 has before the secret code? – schrodigerscatcuriosity Apr 10 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 at 15:57
  • I Have updated the question with actual text, – Arjun P Apr 10 at 16:01
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.

| improve this answer | |
  • 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 at 16:40
  • @ArjunP Yes, it is correct, except that you forgot to escape parenthesis with the backslash. You don't need the backslashes if you also give the -E flag to sed. – Quasímodo Apr 10 at 18:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.