0

I'm doing some web development and I am printing out some object data in the console. I want to target one property/field denoted in output as dataURI: DFASDFKAJELKJDFSADFMLAKFJLSKDJFAJSDFL which is a super long string, and shorten it then append with ellipses at say 25 characters. Is there a .bashrc script or command for this? I don't want to get ellipses on entire output, just the dataURI field.

5
  • Your not telling how your printing that data in the console, but assuming that it's a file, perl -pe 's/\b(dataURI:\ s*)(\S{11})\S{3,}(\S{11})/$1$2...$3/g'
    – mosvy
    Apr 6 '20 at 17:42
  • My web application is printing this object from javascript, when certain actions trigger. But I wanted to catch them with bash script rather then change the javascript console.log(). Apr 6 '20 at 17:48
  • Or shorter, and doing actually 25 instead of 24 characters: ... input .. | perl -pe 's/\bdataURI:\s*\S{11}\K\S{4,}(?=\S{11})/.../g'. You can call that from a bash script. Doing string processing in bash is actually not a good idea, so unless you're already having that data in a bash variable, don't get it there with a while IFS= read -r var; do ...; done in the 1st place ;-)
    – mosvy
    Apr 6 '20 at 17:54
  • Oh ok I'll trust you then that it's not a good idea then, I'll find a workaround in javascript, thank you! Apr 6 '20 at 17:57
  • FWIW, my first substitution works exactly the same in javascript as in perl: your_string.replace(/\b(dataURI:\ s*)(\S{11})\S{4,}(\S{11})/g, "$1$2..$3")
    – mosvy
    Apr 6 '20 at 18:07
4

You could use

printf "%.25s...\n" "dataURI: DFASDFKAJELKJDFSADFMLAKFJLSKDJFAJSDFL"

Or you can use parameter expansion:

echo "${yourvar:0:25}..."

Though with both of these if your string is shorter than 25 characters it'll still include the ellipsis.

3
  • It is printing from web application using javascript console.log(). Apr 6 '20 at 17:50
  • 3
    @ArielFrischer ... then why in the world is this tagged bash, shell, and shell-script?
    – Shawn
    Apr 6 '20 at 17:52
  • Because I wanted to catch it with bash script, and do it selectively for different fields. The output is in my bash terminal. Apr 6 '20 at 17:54

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.