Search code examples
unixsedtext-processing

Replace groups of characters by newline


I have a line with ', ' in my file, and I want to replace this with an new line

Input:

['siteed01pg|10.229.16.153|10.229.0.0|19|test / crt|BACKUP_MUT_SD  Vlan981 (PVLAN 1981)  New Backup Subnet #1  (site SD)', 'siteed01pg|10.129.135.53|10.129.135.0|26|test / crt|Fmer  bopreprodback  Vlan 754', '
[...]

My sed command:

sed "s/\', \'/\n/g"

Output:

['siteed01pg|10.229.16.153|10.229.0.0|19|test / crt|BACKUP_MUT_SD  Vlan981 (PVLAN 1981)  New Backup Subnet #1  (site SD)nsiteed01pg|10.129.135.53|10.129.135.0|26|test / crt|Fmer  bopreprodback  Vlan 754n

in my output the line break has been replaced by the character n Why ?


Solution

  • You can use sed like this to use \n in replacement:

    sed "s/', '/"$'\\\n'"/g" file
    

    Here we are using $'\n' to use a newline character in replacement. We ended up using ``$'\\n'due to use of double quotes aroundsed` command.

    As per man bash:

    Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard

    or else with multiline sed:

    sed "s/', '/\\
    /g" file
    

    This will work on both gnu and POSIX sed versions on bash.

    PS: If you're using gnu sed then a simplified command would be:

    sed "s/', '/\n/g" file
    
    ['siteed01pg|10.229.16.153|10.229.0.0|19|test / crt|BACKUP_MUT_SD  Vlan981 (PVLAN 1981)  New Backup Subnet #1  (site SD)
    siteed01pg|10.129.135.53|10.129.135.0|26|test / crt|Fmer  bopreprodback  Vlan 754
    
    [...]