Search code examples
bashshellsedsubstring

Using sed command in shell script for substring and replace position to need


I’m dealing data on text file and I can’t find a way with sed to select a substring at a fixed position and replace it.

This is what I have:

X|001200000000000000000098765432|1234567890|TQ

This is what I need:

‘X’,’00000098765432’,’1234567890’,’TQ’

The following code in sed gives the substring I need (00000098765432) but not overwrites position to need

echo “ X|001200000000000000000098765432|1234567890|TQ” | sed “s/
*//g;s/|/‘,’/g;s/^/‘/;s/$/‘/“

Could you help me?


Solution

  • If you want to put the quotes in, I'd still use awk.

    $: awk -F'|' 'BEGIN{q="\047"} {print  q $1 q","q substr($2,17,14) q","q $3 q","q $4 q"\n"}' <<< "X|001200000000000000000098765432|1234567890|TQ"
    'X','00000098765432','1234567890','TQ'
    

    If you just want to use sed, note that you say above you want to remove 16 characters, but you are actually only removing 14.

    $: sed -E "s/^(.)[|].{14}([^|]+)[|]([^|]+)[|]([^|]+)/'\1','\2','\3','\4'/" <<< "X|0012000000000000000098765432|1234567890|TQ"
    'X','00000098765432','1234567890','TQ'