Awk / Bash将数字从行前移到行尾

时间:2018-03-17 11:04:06

标签: bash awk

我想将数字/数字字符串从行前移到行尾,输入示例:

123example
321example
34292example

预期产出:

example123
example321
example34292

5 个答案:

答案 0 :(得分:5)

GNU awk的match函数可以完成这项工作:

gawk 'match($0, /^([0-9]+)(.*)$/, m) {print m[2] m[1]}' yourfile.txt

但老实说,我会使用sed来完成这项任务(正如@anubhava建议的那样)。

答案 1 :(得分:2)

使用bash和正则表达式:

s="123example"
[[ $s =~ ([0-9]+)(.*) ]] && echo "${BASH_REMATCH[2]}${BASH_REMATCH[1]}"

输出:

example123

答案 2 :(得分:1)

GNU awk

awk -F"[[:digit:]]+" '{split($0,f,FS,s); print $2 s[1]}' file
example123
example321
example34292

您可以将数字流用作FS。使用FS拆分字符串,匹配分隔符的字符将存储在数组s中。随意使用

答案 3 :(得分:1)

关注awk可以在array中不使用match的情况下为您提供帮助:

awk '{gsub(/\r/,"");match($0,/^[0-9]+/);print substr($0,RSTART+RLENGTH+1) substr($0,RSTART,RLENGTH)}' Input_file

现在还添加了gsub(/\r/,""),用于从Input_file中删除所有回车。

如果您想将输出保存到Input_file本身,请在上面的代码> temp_file && mv temp_file Input_file附加

说明: 现在也在这里添加说明。

awk '
{
  gsub(/\r/,"")                                              ##Removing all carriage returns from current line here by using gsub out of box function of awk.
  match($0,/^[0-9]+/);                                       ##Using match function of awk to match starting digits in current line.
  print substr($0,RSTART+RLENGTH+1) substr($0,RSTART,RLENGTH)##Printing substrings here 1st substring is to print from the value of RSTART+RLENGTH+1 to till the end of the line and second substring is to print from the RSTART to RLENGTH where RSTART and RLENGTH are the variables of awk which will be SET once match is having a TRUE value in it. RSTART denotes the index value of matched regex in line/variable and RLENGTH is the length of the matched regex by match.
}
' Input_file                                                ##Mentioning the Input_file name here.

答案 4 :(得分:0)

首先删除示例并将其放回到左边的前面。

awk '{sub(/example$/,"");print "example"$0}' file

example123
example321
example34292