Thread RegEx für Trim und aus Multiline eine Zeile machen (8 answers)
Opened by mika at 2018-02-27 15:33

Linuxer
 2018-02-27 19:48
#188059 #188059
User since
2006-01-27
3891 Artikel
HausmeisterIn

user image
Naja, Perl-Einzeiler fristen bei mir das Dasein als "One-Shot". Sobald es in Skripten gespeichert wird, fallen sie raus und es wird aufwendiger, damit es auch später noch leichter nachzuvollziehen ist.

Beispiel:
Code: (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#! /bin/bash

# helper script simulator

VAR=" fu bar\n foo \n\n bar \n\n\n baz "


echo -e "$VAR" | perl -nE '
# this code is used inside a loop because of -n option
s/^\s+//; # remove leading whitespaces from lines
s/\s+$/ /; # replace trailing whitespaces (including newlines) with a single whitespace
$output .= $_; # append to a variable for later output

# at the end, do this
END {
$output =~ s/\s+$//; # remove trailing whitespace
say qq~>$output<~; # testing output
#say $output; # production output
}
' #END_OF_PERL



Man könnte dann den Perl-Anteil auch noch in eine Shell-Funktion packen, und diese Funktion dann in einer Kommando-Kette verwenden.

Beispiel dazu:
Code: (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#! /bin/bash

# helper script simulator

VAR=" fu bar\n foo \n\n bar \n\n\n baz "


make_single_line() {
perl -nE '
# this code is used inside a loop because of -n option
s/^\s+//; # remove leading whitespaces from lines
s/\s+$/ /; # replace trailing whitespaces (including newlines) with a single whitespace
$output .= $_; # append to a variable for later output

# at the end, do this
END {
$output =~ s/\s+$//; # remove trailing whitespace
say qq~>$output<~; # testing output
#say $output; # production output
}
' #END_OF_PERL
}


echo -e "$VAR" | make_single_line | vim -



Und am Ende stellt man das Helferskript einfach komplett auf Perl um ;-)
meine Beiträge: I.d.R. alle Angaben ohne Gewähr und auf Linux abgestimmt!
Die Sprache heisst Perl, nicht PERL. - Bitte Crossposts als solche kenntlich machen!

View full thread RegEx für Trim und aus Multiline eine Zeile machen