0

I have a bash script that has a filename and a string contained within a file and I want to compare a substring from the file against the filename(tar.gz) to see if they match or not.

substr=$(echo "$(cat /home/user/configrc | grep Version)" | cut -d '_' -f4-5)
xfile="/home/user/data_1806_01.tar.gz"
echo $substr
echo $xfile
echo "Is $substr in $xfile"

if [ "$xfile" == *"$substr"* ]; then echo "Match"; else echo "No Match"; fi

the output is as follows

DD_DATA_AB_1806_01
1806_01
/home/user/data_1806_01.tar.gz
 in /home/user/data_1806_01.tar.gz
No Match

I can't get a match to occur, 1806_01 should have the substring match in DD_DATA_AB_1806_01. Also what is strange is that the line - echo "Is $substr in $xfile" does not get printed out properly - "Is $substr" or "Is 1806_01" is missing

Is there some sort of termination that i need at the end of substr??

The file configrc contains the line Version=DD_DATA_AB_1806_01

I have looked at many examples online but can't see what I am doing wrong.... such a simple problem....

Thank you very much :)

Centos 7.2

5
  • Does /home/user/configrc have DOS-style (CRLF) line endings? Oct 16, 2019 at 22:23
  • It may do. I believe the file could have been created in windows - is there a way I can tell?
    – tj26
    Oct 16, 2019 at 22:27
  • Firstly, you don't need to use cat because grep Version /home/user/configrc will send it to standard output. Also, your string doesn't match because it's printing DD_DATA_AB_1806_01 as the value of $substr which doesn't match 1806_01 which is the value of $xfile because it's not piping it into the cut command. Even if it worked, it still wouldn't match because you set _ as a delimiter with the cut command so printing fields 4 and 5 will give you 1806 01 which isn't 1806_01. Oct 16, 2019 at 22:28
  • dos2unix allowed the line "Is 1806_01 in /home/user/data_1806_01.tar.gz". Still didn't match on substring thou
    – tj26
    Oct 16, 2019 at 22:35
  • That makes more sense but it still doesn't match because you set $xfile to /home/user/data_1806_01.tar.gz. You'll have to print the 1806_01 form that to get a match. Oct 16, 2019 at 22:38

1 Answer 1

1

As mentioned in the comments, you don't need echo and cat to grep for the string and you need two brackets for this type of comparison:

substr=$(grep 'Version' /home/user/configrc | cut -d '_' -f4-5)
xfile="/home/user/data_1806_01.tar.gz"

if [[ "$xfile" == *"$substr"* ]]; then
  echo "Match"
else
  echo "No Match"
fi
1
  • don't need grep either: substr=$(awk -F_ -v OFS=_ '/Version/ {print $4, $5}')
    – cas
    Oct 17, 2019 at 7:52

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.