0

I have a file like so:

some line
some other line
DisplayChoices=SAMSUNG
yet another line
ChipManufacturer=LG
and yet another line

( there may be lots more of lines in the file, but the = sign is unique, only present in the lines i want to perform action on)

Now, I need to convert the string after = into a hex representation so eventually it should look like

some line
some other line
DisplayChoices=53,41,4D,53 (etcetera, hex representation, seperated by comma`s)
yet another line
ChipManufacturer=4C,47
and yet another line

I tried sed and od but to no avail, od worked on the complete file, but it I need to only convert the specified strings. Anyone know a solution?

3 Answers 3

3

If Perl is an option:

$ perl -lpe 's#(?<==)(.*)#join ",", unpack("H2" x length($1), $1)#e' file
some line
some other line
DisplayChoices=53,41,4d,53,55,4e,47
yet another line
ChipManufacturer=4c,47
and yet another line

I'm sure this could be improved ...

2

You can avoid the external process calls by setting up an awk array to translate bytes to Hex:

AWK='''
BEGIN {
    FS = "="; OFS = "=";
    for (j = 0; j < 256; j++)
        Hx[sprintf("%c",j)] = sprintf(",%.2X", j);
}
function toHex (tx, Local, j, r) {
    for (j = 1; j <= length (tx); j++)
        r = r Hx[substr(tx, j, 1)];
    return (substr(r, 2));
}
$2 != "" { $2 = toHex( $2); }
{ print; }
'''
awk "${AWK}" myFile

paul--)  awk "${AWK}"  foo.txt
some line
some other line
DisplayChoices=53,41,4D,53,55,4E,47
yet another line
ChipManufacturer=4C,47
and yet another line
ESC,%,TAB,*=1B,25,09,2A
1

Probably not the cleanest way to do it but with awk:

awk -F= -v OFS=\= '$2 != ""{
        "printf "$2" | od -A n -t x1 | tr -s \" \"" | getline $2;
        gsub(/^ | $/,"",$2);
        gsub(/\s/, ",",$2);
}1' input

This will use = as a field separator, and if a second field exists it will execute od -A n -t x1 against it, squeeze all spaces, trim the leading and trailing space, and convert all remaining spaces to a comma.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.