Sample Header Ad - 728x90

Performing character-level comparison of "strings" without explicitly creating temporary files for git diff

0 votes
1 answer
149 views
Referring to this https://stackoverflow.com/a/31356602 , I wrote this code:
#!/bin/bash

# Define the two strings to compare
string1="First string with some random text."
string2="Second string with some random text and some changes."

# Create a temporary directory
temp_dir=$(mktemp -d)

# Create temporary files for the strings
file1="$temp_dir/string1.txt"
file2="$temp_dir/string2.txt"
echo -e "$string1" > "$file1"
echo -e "$string2" > "$file2"

# Use the git diff command to compare the temporary files
git diff --no-index --word-diff=color --word-diff-regex=. "$file1" "$file2"

# Delete the temporary directory
rm -rf "$temp_dir"
that returns: enter image description here Now I'm trying to condensate it in a single line:
#!/bin/bash

# Define the two strings to compare
string1="First string with some random text."
string2="Second string with some random text and some changes."

# Use the git diff command to compare the strings
git diff --no-index --word-diff=color --word-diff-regex=. <('%s\n' "$string1") <(printf '%s\n' "$string2")
but I get: enter image description here How can I pass strings as files to git diff without explicitly creating temporary files? **Note.** My goal is to "visually" compare (character-level) two (short) strings, obtaining an output similar to this: enter image description here in which the differences between the two compared strings are highlighted in a single string. The output of git diff is ideal, but I am also open to other solutions.
Asked by Gabriele (353 rep)
Feb 26, 2024, 05:11 AM
Last activity: Feb 26, 2024, 09:34 PM