i have a file a.txt which contains
"ysm.set.ac4-qa.sds.audit
add yinst setting yti. YTI_
HOST_OVERRIDE ="

I have variable STR which is dynamically assigned the value
"HOST_OVERRIDE="

I need to grep $STR on the file a.txt as `grep "$STR" a.txt `
But because of the spaces before =, the line is not getting printed. But my program definetely needs it to be printed ignoring the spaces. Is there any way to achieve it..?
Please reply any one.

Thanks
Srujana

Dani AI

Generated

— the issue is that your STR has no spaces but the file line does (HOST_OVERRIDE = ...), so a literal grep "$STR" won't match. 's sed-based removal is simple but destroys the original spacing; 's awk trick keeps the printed line intact but removes all spaces from the buffer for matching (which can give false negatives/positives if STR itself contains spaces).

A more precise approach is to compare the left/right sides of the = after trimming only surrounding whitespace, and print the original line unchanged. This one-liner handles multiple = on the right-hand side by recombining fields:

awk -v s="$STR" -F'=' '
BEGIN {
  gsub(/^[ \t]+|[ \t]+$/, "", s)
  split(s, a, "=")
  # recombine right side in case STR has "=" in it
  a_right = a[2]
  for (i=3; i in a; i++) a_right = a_right "=" a[i]
  gsub(/[ \t]+/, "", a[1])
  gsub(/[ \t]+/, "", a_right)
  a[2] = a_right
}
{
  left = $1
  right = $2
  for (i = 3; i <= NF; i++) right = right "=" $i
  gsub(/[ \t]+/, "", left)
  gsub(/[ \t]+/, "", right)
  if (left == a[1] && right == a[2]) print $0
}' a.txt

Notes:

  • This preserves the original line formatting and only ignores whitespace around =.
  • If you need a grep-based solution instead, build a regex from STR that replaces = with [[:space:]]*= (and escape regex metacharacters in STR first). Be careful: escaping and portability (e.g., grep -P) vary across systems.

Recommended Answers

All 3 Replies

Member Avatar for Member #585571

Option #1:

Remove space from a.txt

Option #2:

Use this code -

sed 's/\ //gi' a.txt | grep "$STR"
Member Avatar for Member #585571

One more method I found is to use sed to trim infinite white spaces. The code I posted previosuly works only for single space.

Here's the code for infinite spaces -

sed -r 's/[ ]+//gi' a.txt | grep $STR

You might want to try

awk 'BEGIN{ str="'"${STR}"'" }{ buf=$0; gsub(/ /, "", buf) } buf ~ str { print }' a.txt

which should print the "matched" line untouched.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.