3

Given these two strings:

"12345"
"1245"

Where the first one is the complete string and the second has things missing from the first, I want it to return "3".

So again with:

"The ball is red"
"The is red"

I want to to return "ball"

I've tried diff with:

diff <(echo "12345") <(echo "1245")

But diff isn't giving the desired output. comm doesn't do what I want either.

Martin
  • 35,178
  • 15
  • 71
  • 80
clickateclick
  • 31
  • 1
  • 2

2 Answers2

5

I think that comm is the correct command:

comm -23 <(tr ' ' $'\n' <<< 'The ball is red') <(tr ' ' $'\n' <<< 'The is red')

or more flexible:

split_spaces() { tr ' ' $'\n' <<< "$1"; }
split_chars() { sed $'s/./&\\\n/g' <<< "$1"; }
comm -23 <(split_spaces 'The ball is red') <(split_spaces 'The is red')
comm -23 <(split_chars 12345) <(split_chars 1245)
Philipp
  • 45,923
  • 12
  • 81
  • 107
  • 1
    Sort is needed in general case. As in `comm -23 – Sida Zhou May 10 '19 at 05:39
  • Apart from @SidaZhou's addition, it may needs -13 instead of -23 if the sentences were in the opposite order for example. `comm --help` describes it clearly. – nik686 Jan 10 '20 at 21:49
1

Using only one external executable:

a='The ball is red'
b='The is red'
join -v 1 <(echo "${a// /$'\n'}") <(echo "${b// /$'\n'}")

Using join and grep on strings with no spaces:

a=12345
b=1245
join -v 1 <(echo "$a" | grep -o .) <(echo "$b" | grep -o .)
Dennis Williamson
  • 324,833
  • 88
  • 366
  • 429