2

I trying to use sed to remove the linefeed from lines that contain a pattern. My lines are:

              Format:                    0000000
              InputMask:                 &&&&&&&
              OrdinalPosition:           0

              Required:                  True
              SourceField:               LOAN-NO
              SourceTable:               MASTER

I want it to look like this:

              Format:                    0000000
              InputMask:                 &&&&&&&
              OrdinalPosition:           0

              Required:                  True
              SourceField:               LOAN-NO:SourceTable:               MASTER

My code is:

cat file.txt | sed 's/\(*.SourceField.*\)\(\n\)/\1:/g'

The code doesn't change anything. In fact even when I remove the pattern and look for \n it still doesn't work

This seems to work for all lines:

cat file.txt | sed ':a;N;$!ba;s/\n//g' 

but I cant get it to work for just the lines containing with SourceField.

I'd like to understand why the first line doesn't work, and how the second line can be adapted to work with just the lines containing the pattern.

Any help would be appreciated.

Thanks!

C0ppert0p
  • 629
  • 2
  • 7
  • 20

2 Answers2

1
$ sed -E '/SourceField:/{N;s/\n */:/;}' file

              Format:                    0000000
              InputMask:                 &&&&&&&
              OrdinalPosition:           0

              Required:                  True
              SourceField:               LOAN-NO:SourceTable:               MASTER

your first script won't work because sed operations are line based. In the pattern space you can remove the new line.

karakfa
  • 62,998
  • 7
  • 34
  • 47
0

Using in multiline context (kind of natural):

perl -0 -pe 's/(\s+SourceField:\s+LOAN-NO)\n\s+/$1:/' file
  • the \s+ are spaces (or blanks). Isn't a clear and readable code ?
  • the -0 makes Perl to slurp the whole file in a single string variable

          Format:                    0000000
          InputMask:                 &&&&&&&
          OrdinalPosition:           0

          Required:                  True
          SourceField:               LOAN-NO:SourceTable:               MASTER
Gilles Quenot
  • 143,367
  • 32
  • 199
  • 195