将行的子文本前置到同一行

时间:2014-09-14 18:43:52

标签: bash perl shell

如何从文件中获取:

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+/$&, $`$&$'/

3 个答案:

答案 0 :(得分:3)

使用perl one-liner

perl -ne 'print "$1, $_" if /(\d+)/' filename

切换

  • -n:为输入文件中的每个“行”创建一个while(<>){...}循环。
  • -e:告诉perl在命令行上执行代码。

答案 1 :(得分:2)

sed -En 's/.*([0-9]+).*/\1, &/p' filename

答案 2 :(得分:2)

从命令行使用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