我想做以下事情:
- 抓取两个标记之间的所有文本
someFile.txt
- 将文本放入一个数组中,该数组被分割为
\n
- 按字母顺序对数组进行排序
- 将两个标记之间的文本替换为
someFile.txt
按字母顺序排列的版本。
someFile.txt
操作前:
// __MARKER__
../library/_shared/_shared/components/InfoPill/InfoPill.stories
../library/_shared/_shared/components/IconChevronRightBlack/IconChevronRightBlack.stories
../library/_shared/_shared/components/ButtonPrimary/ButtonPrimary.stories
// __MARKER__
someFile.txt
操纵后:
// __MARKER__
../library/_shared/_shared/components/ButtonPrimary/ButtonPrimary.stories
../library/_shared/_shared/components/IconChevronRightBlack/IconChevronRightBlack.stories
../library/_shared/_shared/components/InfoPill/InfoPill.stories
// __MARKER__
答案1
如果perl
没问题并且文件足够小以满足内存要求
$ perl -0777 -pe 'BEGIN{$m = "// __MARKER__\n"}
s|$m\K.*?(?=\n$m)|join "\n", sort split/\n/,$&|gse' ip.txt
// __MARKER__
../library/_shared/_shared/components/ButtonPrimary/ButtonPrimary.stories
../library/_shared/_shared/components/IconChevronRightBlack/IconChevronRightBlack.stories
../library/_shared/_shared/components/InfoPill/InfoPill.stories
// __MARKER__
-0777
将整个文件作为字符串读取$m = "// __MARKER__\n"
将标记保存在变量中$m\K.*?(?=\n$m)
捕获标记之间的字符串join "\n", sort split/\n/,$&
将捕获的字符串拆分\n
,然后对其进行排序,最后通过连接数组元素得到单个字符串s
允许.
匹配的修饰符\n
e
修饰符以允许替换部分中的代码- 使用
-i
就地编辑选项