regex
linux
shell
awk
sed
Xiaoer
Xiaoer
发布于 2020-01-19
3 个回答
RavinderSingh13
RavinderSingh13
发布于 2020-01-20
已采纳
0 人赞同

请您尝试以下 tac 。+ awk 的解决方案。

tac Input_file | awk 'FNR==1{sub(/}/,"content&")} 1' | tac

2nd solution: Using GNU sed + tac here.

tac Input_file | sed '1 s/}/content&/' | tac
    
如果 } 总是在第2种解决方案的最后一行,那么通过 sed '$s/\/(.*\)}/content}/' file 可以消除对文件的2次读取。
KamilCuk
KamilCuk
发布于 2020-01-20
0 人赞同

要想只对文件中的最后一行运行命令,只需在其前面加上 $

sed "$s/}$/content&/g"

如果最后一个}应该有前缀,但不在文件的最后一行,我们可以从最后一个}开始保留行,并在最后一行的保留空间中替换}

cat <<EOF |
sometext
sed -n '
    # if the line contains }
        # if there is anything in hold space, print it
        /^$/!p
        # hold current line
        # read next line
    # if the line does not contain }, hold it
    # if this is the last line
        # take hold space
        # replace the } with content}
        # there should be only one }
        s/}/content}/
        # print it

on repl outputs:

{content} sometext

So a oneliner: sed -n '/}/{x;/^$/!p;x;h;b};H;${x; s/}/content}/ ;p}'

这在这个例子中可以正常工作,但如果最后一个匹配不是文件的最后一行,当然就无法工作。
Replace " with ' . In " the $s will expand.
potong
potong
发布于 2020-01-20
0 人赞同

This might work for you (GNU sed):

sed -z 's/\(.*\)}/\1content}/' file

将文件滑入内存,在最后一个}之前插入content

替代方案,也许更节省内存。