1

The Java keytool command is used to manage Java keystores. In this case I am listing the contents of the cacerts file that comes with any Java runtime.The command is:

keytool -list -keystore ./cacerts -storepass somethingorother

The output looks like this:

Keystore type: jks Keystore provider: SUN
Your keystore contains 164 entries
wizardgeneratedalias, Nov 17, 2020, trustedCertEntry, Certificate fingerprint (SHA1):BA:14:BF:5D:17:2F:F8:FE:29:44:90:12:46:C1:46:B1:C6:80:CB:6F securetrustca [jdk], Nov 7, 2006, trustedCertEntry, 
Certificate fingerprint (SHA1): 87:82:C6:C3:04:35:3B:CF:D2:96:92:D2:59:3E:7D:44:D9:34:FF:11

After the header each certificate is presented in two lines, the first starting with the alias of the stored certificate ("wizardgeneratedalias") and ending with "trustedCertEntry," and the second starting with "Certificate fingerprint".

I want to combine these two lines into one on the fly so I can pipe to the next command, whether grep or sort or whatevs.

In vim it's super easy:

:g/trustedCert/s/,$\n/, /

Basically here searching for any (g/) line with string "trustedCert", look for a comma at the end of the line and a newline and replace that with a comma and a space.

I've just never grokked how to do that with awk or sed (not really sed's thing anyway), or perl.

Thanks!

TLP
  • 66,756
  • 10
  • 92
  • 149

4 Answers4

1

Using any awk in any shell on every UNIX box and without reading the whole input into memory (probably not a big deal in this specific case):

$ cat file | awk '{printf "%s%s", $0, (/trustedCertEntry,[[:space:]]*$/ ? "" : ORS)}'
Keystore type: jks Keystore provider: SUN
Your keystore contains 164 entries
wizardgeneratedalias, Nov 17, 2020, trustedCertEntry, Certificate fingerprint (SHA1):BA:14:BF:5D:17:2F:F8:FE:29:44:90:12:46:C1:46:B1:C6:80:CB:6F securetrustca [jdk], Nov 7, 2006, trustedCertEntry, Certificate fingerprint (SHA1): 87:82:C6:C3:04:35:3B:CF:D2:96:92:D2:59:3E:7D:44:D9:34:FF:11

In the above I'm just using cat file in place of whatever command you're running that you want to pipe to awk.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
0

To remove a newline chomp on a line that contains the string trustedCert you can just do this:

perl -pe'chomp if /trustedCert/' 

Depending on how you would use this command, the application varies.

TLP
  • 66,756
  • 10
  • 92
  • 149
0

The direct equivalent would be

perl -pe'/trustedCert/ and s/,\n/, /'

But there's no need to perform two matches.

perl -pe's/trustedCert.*,\K\n/ /'

Specifying file to process to Perl one-liner.


TLP's solution doesn't check for a comma, and doesn't replace the line feed with a space.

ikegami
  • 367,544
  • 15
  • 269
  • 518
0
sed -zn 's/trustedCertEntry,\n/trustedCertEntry, /gp'

Consume the output as a single line and then substitute trustedCertEntry, and a new line with trustedCertEntry, and a space

Raman Sailopal
  • 12,320
  • 2
  • 11
  • 18