查找模式并将其移至行尾

时间:2018-05-16 12:08:06

标签: string bash sed

我正在寻找一种解决方案,可以让我在字符/s_之间找到一个模式,并将其移到行尾。

我假设以下字符串:

"s_check_login_password= s_comm_type=TCPIP s_dest_address=10.55.28.125/22 s_org_address= s_net_proxy= s_ft_proxy="

由此,我想在/字段的s_dest_address之后获取值:22,并将其移至行尾。

我试过了:

sed 's/\([^/\]*[^ s_]* s_\)\(.*;\)/\2\1/'

但我想这不是好方法。有没有办法用sed做到这一点?

2 个答案:

答案 0 :(得分:2)

由于您没有粘贴预期的输出,所以根据您的问题摘要,我只写了这个。

awk 'match($0,/\/[^ s]*/){print substr($0,1,RSTART),substr($0,RSTART+RLENGTH+1),substr($0,RSTART+1,RLENGTH-1)}' Input_file

现在也添加非单线形式的解决方案。

awk '
match($0,/\/[^ s]*/){
  print substr($0,1,RSTART),substr($0,RSTART+RLENGTH+1),substr($0,RSTART+1,RLENGTH-1)
}
'   Input_file

<强> 说明:

awk '
match($0,/\/[^ s]*/){  ##Using match utility to match the REGEX where it should match from / to space s and if REGEX match found then do following:
  print substr($0,1,RSTART),substr($0,RSTART+RLENGTH+1),substr($0,RSTART+1,RLENGTH-1) ##Printing substring from 1st character to till value of RSTART then print substring from value of RSTART+RLENGTH+1 to till end then print substring from RSTART+1 value to till RLENGTH-1 value. Basically RSTART and RLENGTH are the out of the box variable for awk which will be SET when a match is found of REGEX, where RSTART is starting index of match and RLENGTH is the length of the REGEX match.
}
' Input_file           ##Mentioning Input_file name here.

答案 1 :(得分:0)

使用sed

sed -E 's#(.*/)([^ ]*)(.*)#\1\3\2#' infile
  • /更改为#作为sed表达式分隔符,因此无需转义它。
  • ([^ ]*)您的预期匹配(22)。
  • (.*)字符串的其余部分。
  • \1\3\2更改了返回捕获组的顺序。