Search code examples
awksediterationls-colors

Use sed to reformat line, duplicate one section onto the begining of other sections on seperate lines


For LS_COLORS and ~/.dir_colors loading with a filter (sed?) Rather than having "pattern color" "pattern color"... on 10 lines, I'd like to have DEF_COLOR color pattern pattern pattern... on one line. How can sed reformat a line so I can use

DEF_COLOR 31 .tar .tgz .zip .z .gz .bz .tbz .tbz

and get the many lines needed in the actual config file format? Like this...

.tar 31
.tgz 31
.zip 31
.z   31
.gz  31
.bz  31
.tbz 31

Solution

  • Is this what you're trying to do?

    $ cat file
    DEF_COLOR 31 .tar .tgz .zip .z .gz .bz .tbz .tbz
    
    $ awk '{for (i=3;i<=NF;i++) print $i, $2}' file
    .tar 31
    .tgz 31
    .zip 31
    .z 31
    .gz 31
    .bz 31
    .tbz 31
    .tbz 31
    

    If you only want to do that for the line that starts with DEF_COLOR (the only line in the example but maybe you have others) then:

    awk '/^DEF_COLOR/{for (i=3;i<=NF;i++) print $i, $2}' file
    

    The above will behave the same way using any awk in any shell on every Unix box so if you're looking for a solution that's portable across all Unix systems, this is it.