git diffの一時ファイルを明示的に生成せずに「文字列」の文字レベル比較を実行する

git diffの一時ファイルを明示的に生成せずに「文字列」の文字レベル比較を実行する

これを参照してくださいhttps://stackoverflow.com/a/31356602、次のコードを書いています。

#!/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"

返品:

ここに画像の説明を入力してください。

今私はそれを1行に圧縮しようとしています。

#!/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")

しかし、私は次のようになります。

ここに画像の説明を入力してください。

一時ファイルを明示的に生成せずにgit diff文字列をファイルに渡すにはどうすればよいですか?

メモ。私の目標は、2つの(短い)文字列を(文字レベル)「視覚的に」比較して、次のような出力を得ることです。

ここに画像の説明を入力してください。

比較された2つの文字列の違いは、単一の文字列で強調表示されます。出力はgit diff理想的ですが、他のソリューションも開いています。

ベストアンサー1

パイプベースのリダイレクト(例:bashの<()

しかし、zsh-ismsを使うとうまくいきます。一時ファイル拡張子があります=()

#!/usr/bin/zsh
# use zsh instead of 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=. \
    =(printf '%s\n' "$string1") \
    =(printf '%s\n' "$string2")

おすすめ記事