Skip to content

Instantly share code, notes, and snippets.

@lilongen
Last active April 26, 2016 06:54
Show Gist options
  • Save lilongen/be3f905aa1b2cca0312161fb2fbac57f to your computer and use it in GitHub Desktop.
Save lilongen/be3f905aa1b2cca0312161fb2fbac57f to your computer and use it in GitHub Desktop.
perl-edit-file-like-sed, perl stream-edit file like sed, use perl to edit file like sed, sed file using perl
examples:
1). modify file using regular expression pattern single-line mode ( '.' and '\s' match '\n')
perl -i -p0E 's|(<artifactId>api</artifactId>[^<]+<version>)(bbb)(</version>)|\1a\3|g' pom.xml
2). modify file using regular expression pattern multi-line mode
perl -i -pE 's|(<artifactId>api</artifactId>[^<]+<version>)(bbb)(</version>)|\1a\3|g' pom.xml
3). do not modify file actually, just print the changed contents
perl -p0E 's|(<artifactId>api</artifactId>[^<]+<version>)(bbb)(</version>)|\1a\3|g' pom.xml
4). unnamed group/backreferences
pattern: (?<name>groupPattern)
backreference in pattern: \g1, \g2, ...
backreference in replace: ${1}, ${2}, ...
perl -p0E 's|(<stringProp name="Argument.name">ServerIP</stringProp>\s+<stringProp name="Argument.value">)[\w\.]+(</stringProp>)|${1}1.1.1.1${2}|g' /tech/api.jmx
5). named groups/backreferences
pattern: (groupPattern)
backreference in pattern: \g{name}
backreference in replace: $+{groupIndex}
perl -p0E 's|(?<g1><stringProp name="Argument.name">ServerIP</stringProp>\s+<stringProp name="Argument.value">)[\w\.]+(?<g2></stringProp>)|$+{g1}1.1.1.1$+{g2}|g' /tech/api.jmx
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment