Search code examples
arraysbashreplacebuilt-in

Bash builtin (not SED!) search and replace using octal values


I'm having problems getting my code to work:

for (( c=1; c<=$DirsArrCnt; c=c+$OneDirArrCnt )); do 
    # Replace every occurence of "/" (ASCII d47 o057) in path with "^A" (ASCII 1)
    Hold="${DirsArr[$c]}"
    DirsArr[c]="${Hold//\057/\001}"
done

Originally I skipped the Hold variable and used the array element directly but took that out thinking it was the problem.

Am I specifying the octal value correctly? I believe 57 is the octal value for "/" right?


Solution

  • I think this is what you want :

    DirsArr[c]="${Hold//$'\057'/$'\001'}"
    

    The syntax you use interprets \0 as a literal 0 (i.e. does nothing different compared to not using the backslash). You need the C-style string to have your numeric code interpreted by the shell.