Home > Enterprise >  Remove line break before and after if the line only contains digits
Remove line break before and after if the line only contains digits

Time:05-11

I have strings in the following format:

ABC "123" (123)
Member
100
QWERTY
Parent
2
QWERTY

ABC "321" (12345)
Member
12
QWERTY

ABC "4321" (123456)
Member
12
QWERTY

and from this format need to get the following:

ABC "123" (123)
Member:100:QWERTY
Parent:2:QWERTY

ABC "321" (12345)
Member:12:QWERTY

ABC "4321" (123456)
Member:12:QWERTY

i.e. to remove the line break before and after if the line consists only of a digit. Is there a best cross-platform/POSIX solution? As far as I understand, pure sh can' t do it. Is there only awk, sed?

CodePudding user response:

It is quite easy with "pure sh". A simple state machine suffices:

#!/bin/sh

nl='
'
state=0
while read -r line; do
    case "$state$line" in
        0*)          state=1 out="$line"        ;;
        1|1*[!0-9]*)         out="$out$nl$line" ;;
        2*)          state=1 out="$out$line"    ;;
        *)           state=2 out="$out:$line:"  ;;
    esac
done
printf '%s\n' "$out"

CodePudding user response:

perl in slurp mode:

perl -0000 -pe 's/\n([0-9] )\n/:\1:/g'  input-file
  • Related