如何从文件中获取:
This is a line 2 There is 1 line imagine 3 lines two times two is 4 There is no number here
以下:
2, This is a line 2 1, There is 1 line 3, imagine 3 lines 4, two times two is 4
因此,前缀是从行中检索的,并且可能因行而异。如何在 bash 和 perl 中做到这一点?大致是这样的:
s/d+/$&, $`$&$'/
使用 perl 单行
代码perl -ne 'print "$1, $_" if /(d+)/' filename
开关:
-
-n
:为输入文件中的每个"行"创建一个while(<>){...}
循环。 -
-e
:告诉perl
在命令行上执行代码。
sed -En 's/.*([0-9]+).*/1, &/p' filename
从命令行使用bash
:
$ while read -r line; do
[[ $line =~ [0-9]+ ]] && echo "${BASH_REMATCH[0]}, $line";
done < file
2, This is a line 2
1, There is 1 line
3, imagine 3 lines
4, two times two is 4