[英]How to insert a text in middle of nth line of file
我正在尝试在文件的第n行之间插入管道符号。 就像diff命令输出中的那个一样。
不想使用VI编辑器。
例如,所需行是文件的第二行:
cat filename
Hi Hi
Hello Hello
This This
is Is
it it
所需的输出:
猫文件名
Hi Hi
Hello | Hello
This This
is Is
it it
您基本上不能通过在行内插入字符来修改某些文本文件。 您需要读取其所有内容,在内存中修改该内容,然后写入新内容。
您可能对GNU ed感兴趣,它可以以编程方式(在某些脚本内)编辑文件。
您可以使用awk
(或任何其他过滤器)并将其输出重定向到某个临时文件,然后将该临时文件重命名为原始文件。
为了您自己的理智,只需使用awk:
$ awk 'NR==2{mid=length($0)/2; $0=substr($0,1,mid) "|" substr($0,mid+1)} 1' file
Hi Hi
Hello | Hello
This This
is Is
it it
要修改原始文件,可以添加> tmp && mv tmp file
,如果您有GNU awk,请使用-i inplace
。
sed '
# select 2nd line
/2/ {
# keep original in memory
G;h
:divide
# cycle by taking the 2 char at the egde of string (still string end by the \n here) and copy only first to other part of the separator (\n)
s/\(.\)\(.*\)\(.\)\(\n.*\)/\2\4\1/
# still possible, do it again
t divide
# add last single char if any and remove separator
s/\(.*\)\n\(.*\)/\2\1/
# add original string (with a new line between)
G
# take first half string and end of second string, and place a pipe in the middle in place of other char
s/\(.*\)\n\1\(.*\)/\1|\2/
}' YourFile
--POSIX
for GNU sed
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.