Search code examples
bashsedline-breaksmultiline

How do I wrap a long sed command embedded within a bash/shell script across multiple lines?


In my shell script I pipe the output of a for loop into an embedded sed command with a long "s|||" substitution statement, as follows:

#/usr/bin/bash

output=/cygdrive/c/output.csv

for i in a b {d..z}
do
    find /cygdrive/$i -type f -name "*.ext" -printf "%p %k\n" |
    sed -e "s|^.\+/\([A-Z]\+\)/\(20..\)/\([0-9]\+\)-\([0-9]\+\)\.bfc\ \([0-9]\+\)|$i,\1,\2-\3-\4,\2,\3,\4,\5|"
done >> $output

The sed command is too long, so my question is how do I wrap the sed line across multiple lines within breaking it?

For example:

#/usr/bin/bash

output=/cygdrive/c/output.csv

for i in a b {d..z}
do
    find /cygdrive/$i -type f -name "*.ext" -printf "%p %k\n" |
    sed -e 
    "s|^.\+/\([A-Z]\+\)/\(20..\)/\([0-9]\+\)-\([0-9]\+\)\.bfc\ \([0-9]\+\)
      |$i,\1,\2-\3-\4,\2,\3,\4,\5|"
done >> $output

Solution

  • Can you put that specific string in a variable like:

    SED_PATTERN="s|^.\+/\([A-Z]\+\)/\(20..\)/\([0-9]\+\)-\([0-9]"
    SED_PATTERN+="\+\)-\([0-9]\+\)\.bfc\ \([0-9]\+\)"
    SED_PATTERN+="|$i,\1,\2-\3-\4,\2,\3,\4,\5|"
    
    for i in a b {d..z}
    do
        find /cygdrive/$i -type f -name "*.ext" -printf "%p %k\n" |
        sed -e "$SED_PATTERN"
    done >> $output
    

    I think that would be the cleanest way.