Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: echoing variable with spaces overlapping string

Tags:

bash

I'm looking for a particular line in a variable, e.g.

echo "$CodeDesc"

0x19 ERASE(6)
0x1A MODE SENSE(6)
0x1B START STOP UNIT
0x1C RECEIVE DIAGNOSTIC RESULTS
0x1D SEND DIAGNOSTIC
0x1E PREVENT ALLOW MEDIUM REMOVAL
0x23 READ FORMAT CAPACITIES
0x24 SET WINDOW

e.g. if I was just looking for "MODE SENSE(6)", I'm using grep and awk (also tried with sed)

desc="$( grep "0x1A" <<< "$CodeDesc" | awk '{print substr($0, index($0,$2))}' )"

This does give me the correct string, i.e. "MODE SENSE(6)" but when I echo it overlaps some of the string:

echo "DESC: \"$desc\""

Gives me:

  "SC:"MODE SENSE(6)

Notice the \" has moved to the beginning and DE is missing.

Later on I'm also printing the same variable along with another variable:

echo -e "${desc}${code}"

I would expect this to print:

MORE SENSE(6) 0x1A 1

But instead I get:

 0x1a 1NSE(6)

I can't figure out what's going on with this, any help would be appreciated.

like image 331
Brian Avatar asked Jan 23 '26 12:01

Brian


2 Answers

Apparently your $CodeDesc is a string made of lines terminated by CRLF. grep and awk faithfully preserve the line ending, and the shell's $() substitution strips off the final LF leaving you with a string that just ends with a CR.

When the CR is printed, the cursor moves to the beginning of the line and whatever gets printed next overwrites what was there.

You can fix this by adding a | tr -d '\015' to your pipeline, or you could do it all in awk including the grep part:

desc="$(awk '{gsub(/\r/,"")} /0x1A/ {print substr($0, index($0,$2))}' <<< "$CodeDesc")"

No awks and greps are needed here.

Bash version > v4:

declare -A codes

while read -r code desc; do
    codes["$code"]=$desc
done <<< "$CodeDesc"

printf 'DESC: "%s"' "${codes['0x1A']}"

Bash version < v4:

while read -r code desc; do
    [[ $code = '0x1A' ]] && printf 'DESC: "%s"' "$desc"
done <<< "$CodeDesc"
like image 41
Gilad Halevy Avatar answered Jan 25 '26 10:01

Gilad Halevy